Using negative css margins

A common design for a widget is a thin border and a caption with a background color that spans the whole widget. This is commonly acheived with something like this:

<div class="pwidget">
	<h2 class="caption">Caption</h2>
	<div class="content">
		Widget content
	</div>
</div>
	
.pwidget {
	border: 1px solid #666666;
	max-width: 15em;
}
.pwidget .caption {
	background-color: #0094FF;
	margin: 0;
	padding: 2px 10px;
}
.pwidget .content {
	padding: 10px;
}
	

Caption

Widget content

This is pretty simple, but we can achieve the same result with less html code. We will eliminate the .content div and move its' padding to the .pwidget div.

To get the same visual result, we need to adjust the .caption margin to -10px -10px 0, the values are 10px because that is the widget's padding. The first value to move the caption up to the widget border and the second value to stretch it out to the vertical egdes of the widget. The third value creates space down to rest of the widget content, resulting in the following code:

<div class="pwidget2">
	<h2 class="caption">Caption</h2>
	Widget content
</div>
	
.pwidget2 {
	border: 1px solid #666666;
	max-width: 230px;
	padding: 10px;
}
.pwidget2 .caption {
	background-color: #0094FF;
	font-size: 1.2em;
	margin: -10px -10px 10px;
	padding: 2px 10px;
}
	

Caption

Widget content

By keeping the top padding on the .pwidget instead of using bottom margin on the caption to create space above the rest of the widget's content, we make sure that the widget will look just fine also without a caption.

I admit that the advantage in this example is not exactly stellar, but it is the simplest way to show the technique that I came up with. This technique can generally be used whenever you want an element to stretch out over the padding of its' parent element. So you can use a general padding on a container element instead of using padding on every child element of the container.

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>