CSS在不影响总体布局情况下让元素自由缩小
CSS在不影响总体布局情况下让元素自由缩小
开始状态
<body>
<div class="box1">box1box1</div>
<div class="box2">box2box2</div>
<div class="box3">box3box3</div>
<div class="box4">box4box4</div>
<div class="box5">box5box5</div>
</body>
<style>
.box1{
height: 100px;
background-color: red;
}
.box2{
height: 100px;
background-color: blue;
}
.box3{
height: 100px;
background-color: green;
}
.box4{
height: 100px;
background-color: gray;
}
.box5{
height: 100px;
background-color: rgb(233, 30, 206);
}
</style>
效果

要求
此时,如果要将class = "box2"的div元素高度由100px变化成50px,而不对总体布局产生变化,即如图

但是如果这里单纯地让box2的height变为50px,如
.box2{
height: 50px;
background-color: blue;
}
会得到下图所示效果,此时box2高度的变化会影响box3 4 5的整体布局

要解决这个问题,可以在class = "box2"的div元素外加一层div元素盒子,把box2的div元素包含在内,然后把该盒子的大小设定为固定值,这样,改变box2的高度就不会对box3 4 5产生变化,具体实现如下。
<body>
<div class="box1">box1box1</div>
<div class="box_0">
<!--class = "box_0的外层盒子"-->
<div class="box2">box2box2</div>
</div>
<div class="box3">box3box3</div>
<div class="box4">box4box4</div>
<div class="box5">box5box5</div>
</body>
<style>
.box1{
height: 100px;
background-color: red;
}
.box_0{
height: 100px;
}
.box2{
height: 50px;
background-color: blue;
}
.box3{
height: 100px;
background-color: green;
}
.box4{
height: 100px;
background-color: gray;
}
.box5{
height: 100px;
background-color: rgb(233, 30, 206);
}
</style>
同样的道理,在img元素中也可以如此应用,使得在不影响总体布局的情况下让图片改变大小。