属性值汇总
属性值 | 说明 |
---|---|
inline | 行元素 |
block | 块元素 |
inline-block | 行内块元素 |
table | 以表格形式显示,类似于table元素 |
table-row | 类似于tr |
table-cell | 类似于td |
none | 隐藏元素 |
block
指的是块元素,有以下特点:
1 独占一行
2 有width和height属性
3 可以定义四个方向的margin
4 内部可以容纳行元素和块元素
inline
指的是行元素,有以下特点
1 可以与其他行元素在同一行
2 无法定义height和width
3 可以定义margin-left和margin-right,但无法定义上下外边距
4 内部只能容纳行元素,不能容纳块元素
inline-block
行内块元素,兼有行元素和块元素特点,最典型的两个例子:img和input。需要注意的是,inline-block元素之间可能会有间隙,我们可以通过给父元素设置font-size:0来去除。
none隐藏元素
我们把它和visibility对照来学,display的none属性和visibility的hidden属性都能够隐藏元素,但使用display属性元素不会占据原有位置,而使用visibility元素被隐藏后仍占据原有位置,例如以下例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>感受隐藏元素的两种方式</title>
<style type="text/css">
.father{
background-color: antiquewhite;
width:260px;
height:120px;
padding:10px;
}
.son1,.son2,.son3{
display: inline-block;
background-color: #1E90FF;
width:80px;
height:120px;
font-size:40px;
text-align: center;
}
</style>
</head>
<body>
<div class="father">
<div class="son1">A</div>
<div class="son2">B</div>
<div class="son3">C</div>
</div>
</body>
</html>
当我们使用display属性隐藏元素:看不见摸不着
.son2{
display:none;
}
当我们用visibility属性隐藏元素:看不见但是摸得着
.son2{
visibility:hidden;
}
table-cell
让元素具备td的特征。该用法非常巧妙,可用于以下三种用途:
图片垂直居中于元素
主要思路:给父元素设置display:table-cell,然后利用text-align设置水平居中,用vertical-aign设置垂直居中。
!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>table-cell妙用</title>
<style type="text/css">
.father{
width:300px;
height:300px;
border:1px solid red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
</head>
<body>
<div class="father">
<img src="img/roll_in.PNG"style="width: 200px;">
</div>
</body>
</html>
等高布局
给左右两盒子都设置display:table-cell属性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>table-cell妙用</title>
<style type="text/css">
.left{
width:240px;
border:1px solid red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.right{
display: table-cell;
border:1px solid red;
width:40px;
}
</style>
</head>
<body>
<div class="left">
<img src="img/roll_in.PNG"style="width: 200px;">
</div>
<div class="right">啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦</div>
</body>
</html>
观察代码我们发现左右盒子是没有定义高度的,盒子的高度由其内容来决定,并且左右两盒子的高度始终相等。这种情况在无法确定高度时非常有用,可以和自适应两栏布局联系起来。
自动平均划分元素
给ul设置table属性值,给li设置table-cell属性值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>table-cell妙用</title>
<style type="text/css">
*{
padding:0;
margin:0;
}
ul{
list-style-type: none;
display:table;
width:300px;
background-color: antiquewhite;
}
li{
color:white;
display:table-cell;
height:60px;
line-height: 60px;
text-align: center;
}
ul li:nth-child(1){background-color: #1E90FF;}
ul li:nth-child(2){background-color: #1E9000;}
ul li:nth-child(3){background-color: #1E90F0;}
ul li:nth-child(4){background-color: #10000F;}
ul li:nth-child(5){background-color: #1E00FF;}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</body>
</html>
当ul的宽度增加时,li元素的宽度也会相应增加,并且仍然平均划分。