Centering a div block without the width using pure CSS (All Browser)

  • Share
  • Share

Easiest way to centering a div using pure CSS

The trick to center the div is to shift the outer and inner div, with the use of position:relative and display:block. Shift the outer block 50% left relative, and then next is to move the inner block back to -50% left. Hope this make sense. This code will work on all browser.

DEMO

html

<body class="ds">
    <div class="wrapper">
        <div class="outer">
            <div class="inner">Centering the DIV</div>
        </div>
    </div>
</body>

css

.ds {
    margin:0;
    padding:0;
}
div.wrapper{
    float: left;
    overflow: hidden;
    position: relative;
    width: 100%;
    background:#00F;
    padding:10px;
    margin:0 -20px;
}
div.outer{
    clear: left;
    float: left;
    left: 50%;
    list-style: none outside none;
    margin: 0;
    padding: 0;
    position: relative;
    text-align: center;
}
div.inner{
    display: block;
    float: left;
    margin: 0;
    padding: 0;
    position: relative;
    right: 50%;
    color:#FFF;
    padding:5px 20px;
    background:#900;
    border:1px dotted #cccccc;
}
Related Posts Plugin for WordPress, Blogger...

I hope you have enjoyed this post, be sure to subscribe to my rss feed by click the subscribe button at the top.

Good Luck!

Be Sure to Subscribe to our feed or follow us on twitter to get the latest updates/patches
End of Article, Thanks for reading.
You can leave a response, or trackback from your own site.

Tags:

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

3 Responses to “Centering a div block without the width using pure CSS (All Browser)

  1. Thanks for the tip. I'm working on html and it's easier to check for any mistakes in the codes if I can center the div.

  2. Tod Break says:

    <img src="http://i1069.photobucket.com/albums/u476/marry38382/1.jpg">
    Ha,Awesome I think it's great

  3. Theresa says:

    I've been looking for a way to center a div without specifying a width all day – I checked at least a dozen sites – this answer was the first to work for me. THANK YOU!!

Leave a Reply