1 Replies - 1622 Views - Last Post: 25 August 2009 - 04:37 PM

#1 crazyjugglerdrummer  Icon User is offline

  • GAME OVER. NERD WINS.
  • member icon

Reputation: 124
  • View blog
  • Posts: 690
  • Joined: 07-January 09

3 ways to center an HTML element with CSS

Posted 25 May 2009 - 07:00 AM

Description: Look at different ways to center an element, from deprecated markup to CSS.Plus 2 deprecated methods. Put an HTML element in the center of the page horizontally, using various techniques.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
    <head>
        <style type="text/css">
            //put styles here (listed below)
        </style>
    </head>
    <body>
        <div id="wrapper">
            <div id="centered_content">This is centered</div>
        </div>
     </body>
</html>

<!-- The way you're probably used to seeing. Allows margin on horizontal
sides to expand as needed to place content in center of containing element-->

#centered_content {
margin: 0 auto;
}

<!-- Typical IE fix. Use text-align: center; on wrapper then use text-align:
left; on centered content to return to normal align-left -->

#wrapper {
text-align: center;
}

#centered_content {
text-align: left;
}

<!-- Interesting way you may not have seen. Position absolutely 50% from 
left edge of containing element, then shift over to the right half of the
centered element's width with negative margin. left: 50%; puts left edge at 
middle of screen, then move over so that the center of the element is at 
the middle of the screen. The distance that you need to move right (from 
the left edge to center of the element) is half of the element's width -->

#centered_content {
position: absolute;
left: 50%;
width: 500px;
margin-left: -250px;
}

<!-- Deprecated old school ways: -->

<center>
    <div id="centered_content">This is centered</div>
</center>


<div id="centered_content" align="center">This is centered</div>




Is This A Good Question/Topic? 0
  • +

Replies To: 3 ways to center an HTML element with CSS

#2 coaster3000  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 99
  • Joined: 28-August 08

Re: 3 ways to center an HTML element with CSS

Posted 25 August 2009 - 04:37 PM

This is actually great for like a tutorial on centering. But its not enough to be a full blown tutorial. Thanks i will keep these in mind
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1