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>凡是到達(dá)了的地方,都屬于昨天。哪怕那山再青,那水再秀,那風(fēng)再溫柔。帶深的流連便成了一種羈絆,絆住的不僅是雙腳,還有未來。</p> <p>怎麼能不喜歡出發(fā)呢?沒見過大山的巍峨,真是遺憾;見了大山的巍峨沒見過大海的浩翰,仍然是遺憾; 見了大海的浩翰沒見過大漠的廣袤,依舊遺憾;見了大漠的廣袤沒見過森林的神秘,還是遺憾。世界上有不絕的風(fēng)景,我有不老的心情。</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>當(dāng)使用浮動(dòng)屬性對(duì)齊,總是包括!DOCTYPE聲明!如果丟失,它將會(huì)在IE瀏覽器產(chǎn)生奇怪的結(jié)果。</p> </div> </body> </html>