开发者

Why is the padding not working on my label elements?

开发者 https://www.devze.com 2023-03-30 00:32 出处:网络
I have some markup here: <label>Username:</label> <div class=\"input small\"><div class=\"left\"></div><div class=\"right\"></div><div class=\"center\"&g

I have some markup here:

<label>Username:</label>

<div class="input small"><div class="left"></div><div class="right"></div><div class="center">
    <input name="username" type="text" />
</div></div>

<label>Password:</label>

<div class="input small"><div class="left"></div><div class="right"></div><div class="center">
    <input name="password" type="password" />
</div></div>

And CSS:

label {
    padding-top: 5px;
}

For some reason, the padding on my two label elements is not working. Tried in IE and Firefox, and it isn't working in either case. F开发者_JAVA百科irebug says the padding is there, but it just isn't doing anything. Tried setting the padding to 50px, and still nothing.

Any ideas?


A label is an inline element and so is not affected by top and bottom padding. You need to make the label a block level element for it to work:

label{
    display: block; /* add this */
    padding-top: 5px;
}


Suggesting a better answer for these reasons:

  • Line height doesn't work right with wrapped lines. It looks messy and spaces the wrapped line above it too.
  • Display block or inline-block cause the label to render below things like a checkbox input placed before it.

The solution is to use a :before or :after pseudo selector on the label. This preserves the native inline behavior but still adds padding/margin/height. Example:

/* to add space before: */

label:before {
  display: block;
  content: " ";
  padding-top: 5px;
}

/* to add space after: */

label:after {
  display: block;
  content: " ";
  padding-bottom: 5px;
}

https://jsfiddle.net/0gpguzwh/


Your labels by default are display:inline and as such, don't support setting of padding. The <div> elements surrounding them start block contexts that make it appear as if your <label>s are also block elements.

You can fix this by adding display:block to the CSS for the label.

Why is the padding not working on my label elements?


Alternatively, you could use the line-height property:

label {
    line-height: 3;
}


Inline elements aren't affected by padding-top. http://jsfiddle.net/pECCX/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号