CSS Horizontal Align
CSS Horizontal Align
Block element alignment
The block element is an element that occupies the full width, with line breaks before and after.
Example of block element:
<h1>
<p>
<div>
In this In this chapter, we will show you how to align block elements horizontally in layout.
Center alignment, use the margin attribute
The block element can set the left and right margins to "automatic" alignment.
Note: Using the margin:auto attribute in IE8 will not work properly unless !DOCTYPE is declared.
The margin attribute can be arbitrarily split into left and right margin settings, and the results are all A centered element appears:
Example
.center { margin-left:auto; margin-right:auto; width:70%; background-color:#b0e0e6; }
Tips: If the width is 100%, alignment has no effect.
Note: There is a margin processing BUG for block elements in IE5. In order for the above example to work in IE5, some additional code needs to be added.
Crossbrowser Compatibility Issues
<pWhen aligning elements like this, it is always a good idea to predetermine the margin and padding of the element. This is to avoid visual differences in different browsers.
IE8 and earlier have a problem when using the position attribute. If a container element (in this case <div class="container">) has a specified width and the !DOCTYPE declaration is missing, IE8 and earlier versions will add a 17px margin to the right. This appears to be a scrolling reserved space. When using the position attribute, always set it in the DOCTYPE declaration!
Use the float attribute to set left and right alignment
Using the float attribute is one of the ways to align elements:
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .right { float:right; width:300px; background-color:#b0e0e6; } </style> </head> <body> <div class="right"> <p>凡是到达了的地方,都属于昨天。哪怕那山再青,那水再秀,那风再温柔。带深的流连便成了一种羁绊,绊住的不仅是双脚,还有未来。</p> <p>怎麽能不喜欢出发呢?没见过大山的巍峨,真是遗憾;见了大山的巍峨没见过大海的浩翰,仍然是遗憾; 见了大海的浩翰没见过大漠的广袤,依旧遗憾;见了大漠的广袤没见过森林的神秘,还是遗憾。世界上有不绝的风景,我有不老的心情。</p> </div> </body> </html>
Crossbrowser compatibility issue
When aligning elements like this, it's always a good idea to predetermine the margin and padding of the element. This is to avoid visual differences in different browsers.
IE8 and earlier have a problem when using float attributes. If a container element (in this case <div class="container">) has a specified width and the !DOCTYPE declaration is missing, IE8 and earlier versions will add a 17px margin to the right. This appears to be a scrolling reserved space. When using the float attribute, always set it in the DOCTYPE declaration!
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body { margin:0; padding:0; } .right { float:right; width:300px; background-color:#b0e0e6; } </style> </head> <body> <div class="right"> <p><b>注意: </b>当使用浮动属性对齐,总是包括!DOCTYPE声明!如果丢失,它将会在IE浏览器产生奇怪的结果。</p> </div> </body> </html>