在web页上的每个元素都是一个盒子,使用display属性可以定义元素的盒类型。对于HTML等文档类型,如果使用display不谨慎会很危险,可能违反HTML中已经定义的现实层次结构,因此使用时需要小心。
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> em { border: 1px solid red; } </style> </head> <body> <div style="width:400px;"> div is the standard <em>block-level</em> element. A block-level element starts on a new line and stretches out to the left and right as far as it can. Other common block-level elements are p and form, and new in HTML5 are header, footer, section, and more. </div> </body> </html>em元素的display属性的默认为inline,在Chrome中效果如下:
em { border: 1px solid red; background-color: red; margin: 12px; padding: 12px; }在Chrome中的显示效果如下:
em { border: 1px solid black; background-color: red; margin: 12px; padding: 12px; width: 100px; display: inline-block; height: 100px; }在chrome中的效果如下:
元素显示为块级元素,元素前后会带有换行符。浏览器的用户代理样式表将一些元素设置到了block,通常是一些容器元素,例如div、section、ul、p和h1,默认情况下(为设置宽度)块级元素将水平扩展占据整个空间。
h3 { display: run-in; }大部分浏览器都不支持该属性。
<div style="display: table;"> <div style="display: table-row;"> <div style="display: table-cell;"> Gross but sometimes useful. </div> </div> </div>
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> div.list { display: list-item; list-style: decimal inside; } </style> </head> <body> <div style="width:400px;"> <div><div class="list">div is the standard block-level element.</div><div class="list">A block-level element starts on a new line and stretches out to the left and right as far as it can.</div><div class="list">Other common block-level elements are p and form, and new in HTML5 are header, footer, section, and more.</div></div> </div> </body> </html>在Chrome中效果如下: