{ text-align: center; } centers inline elements horizontally within their block containers.
Centered text
<img src="image.jpg" alt="alternative text" />
<p>Centered text</p>
img, p { text-align:center; }
{ margin: auto; } centers block elements horizontally within its container.
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
ul { margin:0 auto; width:400px; }
li { float:left; width:33,3%;}
<ul>
<li><a href="#">First item</a></li>
<li><a href="#">Item in the middle</a></li>
<li><a href="#">Last item, no more items</a></li>
</ul>
ul, li { float:left; position:relative; }
ul { left:50%; }
li { right:50%; }
Remember the "good" old table days where vertical alignment was easy? It's still easy or let's say possible. The trick is to get an element behave like a table element.
That's possible by using the display element, { display: table/table-cell; }, but IE 6-7 sadly doesn't support it why we have to do IE 6 and 7 specific markup and styling :(
<ul>
<li>
<a href="#">
<span>Vertical<br />centered<br />text</span>
<!--[if lte ie 7]><b></b><![endif]-->
</a>
</li>
<li>
<a href="#">
<span>Line one<br />Line two<br />Line three</span>
<!--[if lte ie 7]><b></b><![endif]-->
</a>
</li>
<li>
<a href="#">
<span>Only two<br />lines here</span>
<!--[if lte ie 7]><b></b><![endif]-->
</a>
</li>
</ul>
ul { margin:0 auto; width:400px; }
li { float:left; }
a { display: table; height: 100px; }
span { display: table-cell; vertical-align: middle; }
IE 6 + 7 Styling:
span { display: inline-block; }
b { display: inline-block; height: 100%; vertical-align: middle; }
<div class="bg"></div>
.bg { background: url('image.jpg') center center no-repeat; }
Back to blog post (DK)