父元素宽高固定的情况下,子元素为block、inline-block、float时与其宽高100%、auto相互间的影响
以下分三种情况介绍(子元素分别为block、inline-block、float三种情况。每种情况分四类:宽高同为百分比、宽为auto高为百分比、宽为百分比高为auto、宽高同为auto。),文章有点长,结论在文末。
一、子元素display:block;
1.1、子元素宽高都为父元素的百分比。width:70%;与height:100%;
结论:子元素的width和height设置成百分比后,子元素的content内容宽高会根据父元素的width、height来计算。
<body>
<style type="text/css">
.wrapper{
width: 300px;
height: 200px;
background-color: pink;
border: 3px solid red;
}
.one{
width: 70%;
height: 100%;
background-color: #6e95ed;
border: 5px solid;
}
</style>
<div class="wrapper">
<div class="one">A BOX</div>
</div>
</body>
1.2、子元素设置width:auto;height:100%;
结论:子元素宽度设置为auto之后,子元素的width+padding+border+margin的和为父元素的宽度,及子元素的content内容宽度会根据父元素的宽度自适应。
.one{
width: auto;
height: 100%;
background-color: #6e95ed;
border: 5px solid;
margin: 20px;
}
1.3、子元素设置width: 100%;height: auto;
结论:子元素高度设置为auto的时候,并不会像宽度为auto时一样根据父元素自适应。
.one{
width: 100%;
height: auto;
background-color: #6e95ed;
border: 5px solid;
margin: 20px;
}
1.4、子元素设置width: auto;height: auto;
结论:当宽高都为auto时,只有宽度会自适应,高度auto以实际内容高度支撑。
.one{
width: auto;
height: auto;
background-color: #6e95ed;
border: 5px solid;
margin: 20px;
}
二、子元素设置display:inline-block;
2.1、子元素width:70%;height:100%;(结果同1.1)
.one{
width: 70%;
height: 100%;
background-color: #6e95ed;
border: 5px solid;
display: inline-block;
}
2.2、子元素设置width:auto;height:100%;
结论:在display为inline-block的情况下,宽度为auto,不起作用。
.one{
width: auto;
height: 100%;
background-color: #6e95ed;
border: 5px solid;
display: inline-block;
margin: 20px;
}
2.3、子元素设置width: 100%;height:auto;(结果同1.3)
2.4子元素设置width: auto;height: auto;
三、子元素设置float:left;
3.1、子元素width:70%;height:100%;(结果同1.1、2.1)
.one{
width: 70%;
height: 100%;
background-color: #6e95ed;
border: 5px solid;
/*margin: 20px;*/
float: left;
}
3.2、子元素设置width:auto;height:100%;(结果同2.2)
结论:在display为float的情况下,宽度为auto,不起作用。
3.3子元素设置width: 100%;height:auto;(结果同1.3、2.3)
3.4、子元素设置width: auto;height: auto;(结果同2.4)
以上,可得出结论:
A、当子元素的宽高设置为100%时,会按照父元素的width和height的百分比来计算。border、padding、margin超出的部分会溢出。
B、当子元素的宽度设置为auto时,子元素的width+padding+border+margin的和为父元素的宽度,及子元素的content内容宽度会根据父元素的宽度自适应。
C、当子元素的高度设置为auto时,并不会像宽度设置为auto一样,而是根据子元素里面的内容多少来进行高度自适应。
D、当子元素设置display:inline-block;或者float:left;时,子元素的宽度设置为auto,不起作用。
E、position:absolute;和position:fixed;效果同float。
延伸:
float与inline-block
元素浮动之后,状态会类似于inline-block。但是两者又有区别。行内元素浮动后,内部可设置宽高,块级元素浮动后,多个盒子可排列在一行,直到排满父盒子。
子元素不浮动,display设置为inline-block时,盒子之间会有间隙。消除的方法就是,给父元素添加font-size:0;然后子元素再重新设置font-size。
子元素设置float浮动的话,盒子之间是没有间隙的。
<body>
<style type="text/css">
.wrapper{
width: 300px;
height: 200px;
background-color: pink;
border: 3px solid red;
}
.one{
width: 20%;
height: 70%;
background-color: #6e95ed;
border: 5px solid;
display: inline-block;
/*float: left;*/
}
</style>
<div class="wrapper">
<div class="one">A BOX</div>
<div class="one">A BOX</div>
<div class="one">A BOX</div>
</div>
</body>