I\'ve never been totally satisfied with my various solutions to centering content in a web page. the
tag has been deprecated back in the middle of th
Is this what you are looking for ?
<div style=" position: absolute;
display: inline-block;
top: 20%;
bottom: 20%;
right: 20%;
left: 20%;
background-color: #434154;
text-align: center;">
<div style="display: inline-block;
height: 100%;
vertical-align: middle;"></div>
<div style="position: relative;
color: #FFFFFF;
background-color: #546354;
display: inline-block;
vertical-align: middle;">
THIS IS CENTERED WITHOUT SCRIPTING :D
</div>
</div>
If you're sticking with position: absolute;
then set the div that you want things positioned against to have position: relative;
to make it into the positioning context for any child elements.
To center an absolutely positioned div you need to know it's width, then use the following CSS:
#wrapper {
width: 800px;
margin: 0 auto;
position: relative; /* creates a positioning context for child elements */
}
#child {
position: absolute;
width: 400px;
left: 50%;
margin-left: -200px;
}
And the HTML:
<div id="wrapper">
<div id="child">
....
</div>
</div>
You can tweak the width and left margin as you need it (the negative left margin should be half of the width of the div you are centering eg. #child
.
As other people have mentioned using margin: 0 auto;
on an element with a width set on it will center it.
body { text-align: center; }
#wrapper { width: 960px; margin: 0 auto; text-align: left; position: relative; }
#wrapper .child { position: absolute; left: 0; top: 0; }
Just example code, but any .child element would be at 0,0 of the wrapper
Any absolutely positioned element will absolutely position to it's nearest position-relative parent. If an element doesn't have a parent with position relative, it just uses the document. Below is an example without classes (some color and width styles added for clarity).
<html>
<body style="text-align: center;">
<div style="position: relative; width: 100px; height: 100px; margin: 0 auto; background: red;">
<div style="position: absolute; left: 0; top: 0;">
This will absolutely position relative to the container div.
</div>
</div>
<div style="position: absolute; left: 0; top: 0; width: 100px; height: 100px; background: blue;">
This will absolutely position relative to the document
</div>
</body>
</html>