1. 重设父级元素得高度(不建议使用)
<style>
div{
background-color: green;
height: 30px;
width: auto;
margin: 0px;
}
.img1,.img2{
float: left;
opacity: 0.5;
}
</style>
<body>
<div>
<img class="img1" src="../images/2.jpg" height="250px" width="200px"/>
<img class="img2" src="../images/3.jpg" height="200px" width="250px"/>
</div>
</body>
效果是这样的 改div大小300px 可以看到被包括其中了
2. 在所有浮动元素后加一个div标签
<style>
div{
border:3px solid #008000;
width: auto;
margin: 0px;
}
.img1,.img2{
float: left;
opacity: 0.5;
}
.clear{
clear: both;
margin: 0px;
padding: 0px;
border:1px solid red;
height: 5px;
}
</style>
<body>
<div>
<img class="img1" src="../images/2.jpg" height="250px" width="200px"/>
<img class="img2" src="../images/3.jpg" height="200px" width="250px"/>
<div class="clear"></div>
</div>
</body>
3. 为父级元素增加overfloat属性
大多数情况下是hidden,也可以用auto。但用hidden可以保证父类内容不可见,auto超出会加入滚动条
<style>
div{
border:1px solid green;
width: auto;
margin: 0px;
overflow: hidden;
}
.img1,.img2{
float: left;
opacity: 0.5;
}
</style>
<body>
<div>
<img class="img1" src="../images/2.jpg" height="250px" width="200px"/>
<img class="img2" src="../images/3.jpg" height="200px" width="250px"/>
</div>
</body>
4. 用代码添加div
用伪类实现代码添加div,避免加入了空的div标签
<style>
div{
border:3px solid #008000;
width: auto;
margin: 0px;
}
.img1,.img2{
float: left;
opacity: 0.5;
}
.content::after{
content: "";
display: block;
clear: both;
}
</style>
<body>
<div class="content">
<img class="img1" src="../images/2.jpg" height="250px" width="200px"/>
<img class="img2" src="../images/3.jpg" height="200px" width="250px"/>
</div>
</body>
|