Home > Article > Web Front-end > About the CSS control of DIV horizontal centering_html/css_WEB-ITnose
Regarding the issue of CSS controlling the horizontal centering of DIVs, I see that many newcomers are confused. I remember the first time I read CSS was a book written by a foreigner, and it talked about the use of centering.
margin-left:auto;
margin-right:auto;
In fact, it is equivalent to:
margin:0 auto;
So you can Use this method, but some people found that it was not centered when using IE. It is recommended that you check if you are missing a DTD declaration.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
Many people have made similar mistakes! This method can also be said to have been tried and tested, but it still doesn't work in some cases. So there is a second method.
margin-left:50%;
left: -width/2;
The width here is not the Width in CSS, but the width of your DIV. For example, your div is 768px wide, then you should set left:-384px. Very good, there are already two methods, which can be said to have solved the problems you may encounter.
Sometimes you will find that these two are not enough. Not compatible with some browsers. So I found a third method, which mainly considers IE, and is based on the first method. It requires setting body.
Body {text-align: center;}
This way, it is also centered under IE, but it brings a new problem. You find that all the text in your page is centered. This doesn't look good. This is easy to solve, just add text-align: left; and other adjustment settings to your DIV definition.
The above text is just an after-dinner reference and sketch. Everyone can pay attention to it in actual work!