Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

html - CSS child element not recognizing parent for proper alignment

I'm trying to align label text with its corresponding input field using absolute positioning. However, the label is not recognizing my input-div as its parent and seems to be positioning the label text in relation to the outer login-div instead.

HTML:

<div class="login-div">
        <form action="" class="form">
            <h2>Login</h2>
            <div class="input-div">
                <input type="text" name="loginName" id="loginName" required>
                <label for="loginName">Username</label>
            </div>
            <div class="input-div">
                <input type="password" name="loginPassword" id="loginPassword" required>
                <label for="loginPassword">Password</label>
            </div>
            <input type="submit" value="Login" class="submit-btn">
            <a href="#forgot-pw" class="forgot-pw">Forgot your password?</a>
            <p>New member? <a href="#register" class="register">Sign up now!</a></p>
        </form>
</div>

CSS:

.form .input-div label {
  position: absolute;
  top: 0;
  left: 0;
  padding: 10px 0;
  font-size: 1rem;
  pointer-events: none;
}

Login and password crammed into corner of form instead of within the input fields

question from:https://stackoverflow.com/questions/65873803/css-child-element-not-recognizing-parent-for-proper-alignment

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With absolute positioning, you've broken free of the parent box. Adding position: relative; to the input-div element, or changing the label to position relative; may help you position the label in relation to input-div.

.form .input-div {
  position: relative;
}

.form .input-div label {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;  /* Set width to something appropriate */
  height: 30px;  /* Set this value to something appropriate */
  display: table; /* Optional. May help set an organic line width */
  padding: 10px 0;
  font-size: 1rem;
  pointer-events: none;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...