问题
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. Firebug says the padding is there, but it just isn't doing anything. Tried setting the padding to 50px, and still nothing.
Any ideas?
回答1:
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;
}
回答2:
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.

回答3:
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
blockorinline-blockcause thelabelto 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/
回答4:
Inline elements aren't affected by padding-top. http://jsfiddle.net/pECCX/
回答5:
Alternatively, you could use the line-height property:
label {
line-height: 3;
}
来源:https://stackoverflow.com/questions/7168658/why-is-the-padding-not-working-on-my-label-elements