Categories
Uncategorized

How to center divs within a page with CSS

Sometimes you may want to center a div element within a page, whether vertically, horizontally, or both (dead center). Here’s how you can accomplish all of that using CSS.

Sometimes you may want to center a div element within a page, whether vertically, horizontally, or both (dead center). Here’s how  you can accomplish all of that using CSS.

What you need:

The HTML

For this example, we’ll use the following HTML code:

<div id="container">
<p>Some content goes here.</p>
</div>

The CSS

The basic formatting for the #container element will be:

#container {
border: 1px solid #000;
background-color: #69C;
padding: 8px;}

Getting it done:

How to center a div element horizontally

To center a div element horizontally you need to:

  1. Set its left and right margins to auto,  which will automatically set the margin space on both sides of the div element, centering it within the page.
  2. Declare the div element’s width to override the default width: auto property, which makes div elements be as wide as their containers .
Here’s the CSS:
.center_horiz{
 width: 158px;
 margin: 0 auto;
}

See example here

How to center a div element vertically

To center a div element vertically vertically within a page, you need to:

  1. Set the position of the element to absolute, so it uses the height of the page as reference.
  2. Set the top property to 50%, so the div element moves down to the middle of the page
  3. Use the margin-top property to move the div element a little bit above the middle of the page (if you need to).
Here’s the CSS:
.center_vert{
 position: absolute;
 top: 50%;
 margin-top: -35px;
}

See example here

How to center a div element both vertically and horizontally (dead center)

To place a div element dead center within a page, you can use the same technique as when centering it vertically and apply it to center the div element horizontally as well. To accomplish this, you need to:

  1. Set the position of the div element to absolute, so it uses the height and width of the page as reference.
  2. Set the top and left properties to 50%, so the div element moves down and to the center of the page.
  3. Use the margin-top and margin-left properties to move the div element a little bit above and left of the middle of the page (if you need to).
Here’s the CSS:
.dead_center{
 position: absolute;
 top: 50%;
 left: 50%;
 margin-top: -35px;
 margin-left: -85px;
}

See example here

And that should be it. See you next time.

Leave a Reply

Your email address will not be published. Required fields are marked *