Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center div?

I have a problem with centering div in HTML (vertical & horizontal). My code looks something like this:

<div id="container">SOME HTML</div>

#container{
    width: 366px;
    height: 274px;
    margin: 50%;
    top: -137px;
    left: -188px;
    position:absolute;
}

Only chrome center this div in to the middle of the screen.

like image 220
What Avatar asked Apr 24 '12 15:04

What


4 Answers

This will center the <div> horizontally:

#container{
    width: 366px;
    height: 274px;
    margin: 0 auto;
}

Centering vertically is not quite simple, you maybe have to use javascript for that, or you try this css solution.

like image 161
Yogu Avatar answered Oct 31 '22 04:10

Yogu


#container{
    width: 366px;
    height: 274px;
    top: 50%;
    left: 50%;
    margin: -137px 0 0 -188px;
    position:absolute;
}
like image 21
methodofaction Avatar answered Oct 31 '22 03:10

methodofaction


This does the trick (vertical & horizontal):

#container{
    position: absolute;
    width: 366px;
    height: 274px;
    left: 50%;
    top: 50%;
    margin-left: -183px; /* half width */
    margin-top: -137px; /* half height */
}
like image 42
sp00m Avatar answered Oct 31 '22 03:10

sp00m


You could use:

#container {
    // Your other values, but remove position: absolute;
    margin: 0 auto;
}

Alternatively, you can do:

#wrapper, #container {
    border: 1px solid red;
    height: 500px;
    width: 600px;
}

#wrapper {
    bottom: 50%;
    right: 50%;
    position: absolute;
}

#container {
    background: yellow;
    left: 50%;
    padding: 10px;
    position: relative;
    top: 50%;
}

And you're HTML code:

<div id="wrapper">
    <div id="container">
        <h1>Centered Div</h1>
        <p>
            This div has been centered within your browser window.</p>
    </div>
</div>

That will center the <div> in the middle of the browser window.

like image 29
Neil Knight Avatar answered Oct 31 '22 03:10

Neil Knight