willzyx
willzyx

Reputation: 3

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

Upvotes: 0

Views: 580

Answers (3)

Benson
Benson

Reputation: 4391

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;
}

Upvotes: 1

Nikhil Tomy
Nikhil Tomy

Reputation: 73

Try to use transform property

top and left properties rely on the parent's position (relative it, absolute or static). Translations are not affected by that settings. Translation transformations are "identical" to applying top and left when element has position: relative

form .input-div label {
  position: absolute;
  transform: translate(50%, 100%);
  padding: 10px 0;
  font-size: 1rem;
  pointer-events: none;
}

Upvotes: 0

Tch
Tch

Reputation: 1055

the class .input-div should be { position: relative; } otherwise it will be positioned against the closest parent with {position:relative}

it should also have width equals to .form, equals to .login-div

Upvotes: 0

Related Questions