CSS Vertical Padding in a Span Element

If you have worked with CSS a fair amount then you are undoubtedly familiar with the span element. And if you have worked with the span element then you have likely scratched your head and possibly pulled out some hair trying to apply vertical margins or padding to it.

The fact is that span elements are inline elements. Content that is inserted after an inline element will continue on the same line whereas content following block elements will start on a new line. For this reason top and bottom padding cannot be added to a span element. Left and right padding can be added to a span element but top and bottom padding cannot be added without additional coding.

A CSS Trick

What do you do if you have a span element that needs top or bottom padding? The answer is to change its behavior to a block element. Add the display:block style to the span element that needs vertical padding and the top/bottom padding will work since the span element will now be treated as a block element.

Code Example

<style type="text/css">
.header { background-color:yellow; height:30px; }
.header span { display:block; font-weight:bold; padding-left:20px; padding-top:6px; }
<div class="header"><span style="">Shipment Information</span></div>

The header CSS class sets the element height at 30 pixels with a yellow background. The 2nd line in the style section tells the page to render any span element inside an element with the header class to render it as a block element. This allows the padding styles to take effect. Without the display:block style the padding would be ignored. See the code in action below.

Shipment Information

This entry was posted in Web Development and tagged . Bookmark the permalink.