A simpler way to right-align a block-level element

The standard way to right-align a block-level element is to float it. It works well and is simple if you don’t mind that the following content creeps up beside your element. If you want that, fine. If not, you need to add a clearfix hack or make sure that the following content content clears your element.

A different and simple way to achieve the right-alignment that also makes sure that following content doesn’t creep up can be achieved with some margin-trickery.

As a start, we take a look at the html and css that is used to center a block-level element within its parent:
<div class="parent">
<div class="block">
</div>
<p>Some other content</p>
</div>

.parent {
border: 1px solid black;
width: 500px;
}
.block {
background-color: blue;
margin-left: auto;
margin-right: auto;
height: 100px;
width: 250px;
}

background-color, height and border are only included to visualize the elements.

What we want to achieve is simply done by setting the right margin to zero:
.block {
background-color: blue;
margin-left: auto;
margin-right: 0;
height: 100px;
width: 250px;
}

This also has the added benefit of introducing less side effects for older versions of Internet Explorer than the use of floating. Handy if you or your clients care about that.

View sample page

Comments are closed.