display常用的几个属性值:
none : 隐藏元素
block : 块元素,独占一行,在没有设置高度的情况下,高度由内容撑开
inline : 行内元素,对width,height,margint-top,margin-bottom,padding-top,padding-bottom不起作用
inline-block : 行内块元素,其宽度和高度由内容决定
list-item : 元素会作为列表显示
table : 此元素会作为块级表格来显示
inline-table : 作为内联表格来显示
table-row-group : 作为一个或多个行的分组来显示
table-header-group : 作为一个或多个行的分组来显示
table-footer-group : 作为一个或多个行的分组来显示
table-row : 作为一个表格行来显示
table-column-group : 作为一个或多个列的分组来显示
table-column : 作为一个单元格列显示
table-cell : 作为一个表格的单元格显示
table-caption : 作为一个表格标题显示
1. inline元素,我们共处一行吧
<style type="text/css">
*{
margin:0;
padding:0;
}
div{
display:inline;
background-color:red;
}
</style>
<body>
<div>item1</div>
<div>item2</div>
</body>
复制代码
运行结果如下:
从运行结果,我们发现,两个inline元素,中间有个间距,其实,这个间距与display无关,是由于换行或者回车导致的,那么,我们怎么去掉这个间距呐?<body>
<div>item1</div><div>item2</div>
</body>
复制代码
还有一种方法是,将父元素的font-size:0px,然后,再分别设置各个子元素的font-size属性,也可以去掉这个间距。
<style type="text/css">
*{
margin:0;
padding:0;
}
.box{
font-size:0;
}
.box div{
display:inline;
font-size:16px;
background-color:red;
}
</style>
<body>
<div class="box">
<div>item1</div>
<div>item2</div>
</div>
</body>
复制代码
运行结果如下所示:
2. list-item元素作为列表显示
<style type="text/css">
*{
margin:0;
padding:0;
}
.box .item{
display:list-item;
list-style-position: inside;
}
</style>
<body>
<div class="box">
<div class="item">item-1</div>
<div class="item">item-2</div>
<div class="item">item-3</div>
</div>
</body>
复制代码
运行结果如下:
3. 实现表格的效果
<style type="text/css">
*{
margin:0;
padding:0;
}
.table{
display:table;
width:100%;
box-sizing:border-box;
border-collapse:collapse;
}
.table .row{
display:table-row;
}
.table .cell{
display: table-cell;
height:35px;
line-height:35px;
border:1px solid #dedede;
text-align:center;
}
.table .caption{
display: table-caption;
height:35px;
line-height: 35px;
text-align:center;
}
</style>
<body>
<div class="table">
<div class="caption">这是一个表格</div>
<div class="row">
<div class="cell">item1</div>
<div class="cell">item1</div>
<div class="cell">item1</div>
</div>
<div class="row">
<div class="cell">item2</div>
<div class="cell">item2</div>
<div class="cell">item2</div>
</div>
</div>
</body>
复制代码
运行效果如下:
4. 制作垂直水平居中
<style type="text/css">
*{
margin:0;
padding:0;
}
.box{
width:300px;
height:300px;
display:table;
border:1px solid #dedede;
margin:20px auto;
}
.box div{
display: table-cell;
vertical-align: middle;
}
.box div p{
width:100px;
height:100px;
line-height:100px;
margin:0 auto;
text-align: center;
background-color:pink;
}
</style>
<body>
<div class="box">
<div>
<p>table</p>
</div>
</div>
</body>
复制代码
运行效果如下:
其原理是,使用display:table-cell的元素可以像表格一样使用vertical-align属性,先让它垂直居中,然后再给子元素设置margin:0 auto;就可以了。