ohadinho ohadinho - 5 months ago 11
HTML Question

Center only one element within a div

I have this HTML code:

<div>
<input id="cemail" type="email" name="email" placeholder="Your E-Mail" required>
<span>Proper format "exampel@something.com"</span>
</div>


I've configured 'text-align: center' on the div but unfortunately
span
text is also centered (see the image below).
I need
span
to be near it and not centered.

enter image description here

Answer

You probably should center your parent element, and not div inside form:

.center-form {
  text-align: center;
}

.center-form form {
  display: inline-block;
  text-align: left;
}
<div class="center-form">
  <form action="">
    <div>
      <input id="cemail" type="email" name="email" placeholder="Your E-Mail" required>
    </div>
    <div>
      <input id="cemail" type="email" name="email" placeholder="Your E-Mail" required>
      <span>Proper format "exampel@something.com"</span>
    </div>
    <div>
      <input id="cemail" type="email" name="email" placeholder="Your E-Mail" required>
    </div>
    <button>Submit</button>
  </form>
</div>

Or if you want span not to affect form position, use position: absolute:

.center-form {
  text-align: center;
}

.center-form form {
  display: inline-block;
  text-align: left;
}

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

.center-form form div span {
  position: absolute;
  left: 100%;
  top: 0;
  
  /* for demo */
  white-space: nowrap;
}
<div class="center-form">
  <form action="">
    <div>
      <input id="cemail" type="email" name="email" placeholder="Your E-Mail" required>
    </div>
    <div>
      <input id="cemail" type="email" name="email" placeholder="Your E-Mail" required>
      <span>Proper format "exampel@something.com"</span>
    </div>
    <div>
      <input id="cemail" type="email" name="email" placeholder="Your E-Mail" required>
    </div>
    <button>Submit</button>
  </form>
</div>

Comments