To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
You can use margin:0 auto; to center a div horizontally as long as its width is less than that of the container div.
1) Centering links by putting it inside of a text aligned div. Place the HTML link inside of a div. In the styles for the div, apply text-align:center and make the anchor tag an inline-block (display:inline-block).
HTML:
<div id="something">... content ...</div>
CSS:
#something {
position: absolute;
height: 200px;
width: 400px;
margin: -100px 0 0 -200px;
top: 50%;
left: 50%;
}
The simplest solution is just to use an auto margin, and give your div a fixed width and height. This will work in IE7, FF, Opera, Safari, and Chrome:
HTML:
<body>
<div class="centered">...</div>
</body>
CSS:
body { width: 100%; height: 100%; margin: 0px; padding: 0px; }
.centered
{
margin: auto;
width: 400px;
height: 200px;
}
EDIT!! Sorry, I just noticed you said vertically...the default "auto" margin for top and bottom is zero...so this will only center it horizontally. The only solution to position vertically and horizontally is to muck around with negative margins like the accepted answer.
margin: auto;
try this
#center_div
{
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
Using this:
center-div { margin: auto; position: absolute; top: 50%; left: 50%; bottom: 0; right: 0; transform: translate(-50% -50%); }
You can also set your div with the following:
#something {width: 400px; margin: auto;}
With that setting, the div will have a set width, and the margin and either side will automatically set depending on the with of the browser.
<html>
<head>
<style>
*
{
margin:0;
padding:0;
}
html, body
{
height:100%;
}
#distance
{
width:1px;
height:50%;
margin-bottom:-300px;
float:left;
}
#something
{
position:relative;
margin:0 auto;
text-align:left;
clear:left;
width:800px;
min-height:600px;
height:auto;
border: solid 1px #993333;
z-index: 0;
}
/* for Internet Explorer */
* html #something{
height: 600px;
}
</style>
</head>
<body>
<div id="distance"></div>
<div id="something">
</div>
</body>
</html>
Tested in FF2-3, IE6-7, Opera and works well!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With