Centering things with CSS

Often in CSS we want to center things, either vertically or – much more common – horizontally.  There are different types of centering we can do, and we will look at them separately.

Centering text

To center text within a container element, we use text-align:center, as follows:

<p class=”centeredtext”>This phrase will be centered</p>
<style>
.centeredtext { text-align:center; }
</style>

Which looks like this in the browser:

This phrase will be centered

Centering a block horizontally

To center a block element, like a div, horizontally, we use the margin:auto; property. More specifically, we want to make the left and right margins equal automatically. Note that obviously the element needs a width for this that is not the entire width of the page. Here is the code for a centered div element:

<div class="centeredblock">This block is centered.</div>
<style>
.centeredblock {
   background-color:#aaffaa;
  width:200px;
margin-left:auto;
margin-right:auto;
}
</style>

Which looks like this:

Screen Shot 2014-01-21 at 21.23.12

 

 

You can also center an image like this. But, centering only works with elements that have display mode ‘block’.  And the img element, by default, is not quite ‘block’. So you have to add a rule for that explicitly in css:

<img class="centeredimage">
<style>
.centeredimage {
display:block;
margin-left:auto;
margin-right:auto;
}
</style>

Centering a block vertically

To center a block vertically within another element, give the container element the display property ‘table cell’ and use the vertical-align:middle property, like this:

<div class="container">
  <p>This small paragraph...</p>
</div>
<style>
div.container { 
min-height: 10em; 
display: table-cell; 
vertical-align: middle
}
</style>

That said, actually, for images and text, you can also simply put it between <center></center> tags. But don’t tell anybody we told you that.

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s