Skip to main content

Horizontal and vertical centering with CSS

· 2 min read

One of the most common tasks while designing web pages is centering elements both vertically and horizontally.

To center a block (div, p, h1, and so on) horizontally, the only thing you have to do is to apply a margin auto to it. For example,

.horizontal-align {
margin:0 auto;
width:200px;
}

You have to take into account that a width is necessary.

To center lines of text you can use text-align property. For example

p { text-align: center }
h2 { text-align: center }

If you want to center a block vertically, you can use the padding-top and padding-bottom properties with the same value. If you want to center a text line, you can use line-height

.center-text {
height: 100px;
line-height: 100px;
white-space: nowrap;
}

Another way would be to use a container block with a table display and a content block with a table-cell display and vertical alignment.

HTML

<div id="container">
<div id="content">Content here</div>
</div>

CSS

#container {display: table;}

#content {
display: table-cell;
vertical-align: middle;
}

With CSS3 you can play with position, top and transform properties.

HTML

<div class="container2>
<p>Vertical centered paragraph</p>
</div>

CSS

div.container {
height: 10em;
position: relative }
div.container p {
margin: 0;
position: absolute;
top: 50%;
transform: translate(0, -50%)
}

We can also use transform: translateY(-50%) instead of transform: translate(0, -50%) in the above example.

We can extend this method to center horizontally and vertically at the same time using margin-right and left properties.

HTML

<div class="container2>
  <p>Vertical centered paragraph</p>
</div>

CSS

div.container {
height: 10em;
position: relative
}
div.container p {
margin: 0;
background: yellow;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%)
}

Another way to center horizontally and vertically at the same time might be in same cases:

#container {
position: relative;
}

#content {
width: 50%;
height: 50%;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}