css技巧:table-cell的自动平均划分元素
在进入正题之前,我们先来热热身。利用你所会的css,实现如下图宽度相等的水平排列元素。
你可能已经想到了最直接的方法,定义5个div,定义相同的width、height,再让他们水平排列。
至于怎么水平排列,方法很多,我是用的flex:
<div class="flex-box">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
*{
padding:0;
margin:0;
}
.flex-box{
width:300px;
display:flex;
flex-direction:row;
}
.flex-box div{
width:20%;
height:30px;
line-height: 30px;
text-align: center;
color:white;
}
.flex-box div:nth-child(1){
background:red;
}
.flex-box div:nth-child(2){
background:orange;
}
.flex-box div:nth-child(3){
background:blue;
}
.flex-box div:nth-child(4){
background:green;
}
.flex-box div:nth-child(5){
background:purple;
}
效果截图:
有的朋友已经想到,可以直接用ul列表呀。
这里,我们在上面的题的基础上加大一下难度,要求定义父元素的宽度固定,子元素自动均分宽度。没事嘛,我还是可以用ul啊,float一下,再计算一下每个li的宽度不就好了嘛。
比如我是这样的:
<ul id="ul-row">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
*{
padding:0;
margin:0;
}
#ul-row{
list-style-type: none;
}
#ul-row li{
float:left;
width:50px;
height:30px;
line-height:30px;
text-align: center;
color:white;
}
ul li:nth-child(1){
background:red;
}
ul li:nth-child(2){
background:orange;
}
ul li:nth-child(3){
background:blue;
}
ul li:nth-child(4){
background:green;
}
ul li:nth-child(5){
background:purple;
}
效果截图:
除了上面的两个方法,机智的小伙伴已经想到啦,可以直接用table啊!!!直接排成一排,而且td自己平均划分,占满table元素。
上代码:
<table>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</table>
*{
padding:0;
margin:0;
}
table{
width:300px;
border-collapse: collapse;/*注意清除td元素间的间距哦*/
}
td{
height:30px;
line-height:30px;
text-align: center;
color:white;
}
table td:nth-child(1){
background:red;
}
table td:nth-child(2){
background:orange;
}
table td:nth-child(3){
background:yellow;
}
table td:nth-child(4){
background:green;
}
table td:nth-child(5){
background:blue;
}
效果截图:
差不多了,是时候上出今天的大招,那就是我们的题目上写道的:使用table-cell自动平均划分元素!
先来讲讲它的实现原理吧!原理就是:
当父元素定义“display:table”而子元素定义“display:table-cell”时,如果给父元素
一定的宽度,父元素宽度就会根据子元素的个数进行自动平均划分。
其实和最后一个方法很相似,只不过是用display将元素变形成table,table-cell了,但我们不用定义table,td元素了,是不是又感觉get了一个新的知识点。好了,不废话了,一起看看代码是如何实现的吧:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
*{
padding:0;
margin:0;
}
ul{
list-style-type: none;
display:table;/*注意是table,不是table-row*/
width:300px;
}
li{
display:table-cell;
height:30px;
line-height:30px;
text-align:center;/*使文本水平垂直居中*/
color:white;
}
ul li:nth-child(1){
background:red;
}
ul li:nth-child(2){
background:orange;
}
ul li:nth-child(3){
background:blue;
}
ul li:nth-child(4){
background:green;
}
ul li:nth-child(5){
background:purple;
}
效果截图:
怎么样?代码比上面的其他的方法都要简洁吧,而且,ul 元素宽度自动根据 li 元素个数进行平均划分,并不需要我们指定每一个 li 元素的宽度。是不是感觉又get了一个实用的css技巧了呢ε≡٩(๑>₃<)۶