Let's first look at my simple XHTML/HTML file code (part). Our purpose is to center #container horizontally.
<body>
<div id="container">
<h1>content</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus varius eleifend.</p>
</div>
</body>Use adaptive margins (auto margin)
The preferred way to center any element horizontally is to use the margin property and set the left and right values to auto. But you must specify a width for #container.
div#container {
margin-left: auto;
margin-right: auto;
width:168px;
}
This solution works on any modern browser, even IE6, as long as it is in web standards compliance mode. Unfortunately it won't work in previous versions of IE/Win. We make a table for this: Browsing adaptive border support list Browser version support
Internet Explorer 6.0, compliance mode Yes
Internet Explorer 6.0, quirks mode No
Internet Explorer 5.5 Windows No
Internet Explorer 5.0 Windows No
Internet Explorer 5.2 Macintosh Yes
All current versions of Mozilla are
All versions of Mozilla Firefox are
Netscape 4.x No
Netscape 6.x+ Yes
Opera 6.0, 7.0 Macintosh and Windows Yes
Safari 1.2 Yes
Although limited by browser support, most designers encourage you to do this whenever possible. But we can still use CSS for all situations. Using text alignment (text-align) This solution requires the use of the text-align property, which is applied to the body element and assigned the value of center.
body{
text-align:center;
}
It does justice to all browsers, is thorough, and is at your fingertips. However, this is a property given to the text, which causes the text in the #container to be centered as well. Therefore, we have to do some additional work on layout:
div#container{
text-align: left;
}
In this way, the text alignment can be returned to the default state. Integrated borders and text alignment. Because text alignment is backward compatible and contemporary browsers also support adaptive borders, many designers combine them to achieve cross-browser use.
body{
text-align: center;
}
#container {
margin-left: auto;
margin-right: auto;
border: 1px solid red;
width: 168px;
text-align: left
}
Alas, it's still not perfect because it's still a hack. You have to write redundant rules for text arrangement. But now, we can use a more perfect cross-browser solution.
Negative boundary solution