html 浮动布局换行
时间: 2023-09-23 14:07:20 浏览: 63
当浮动元素宽度之和超过其父元素宽度时,会出现浮动元素换行的情况。这时可以通过以下方式来解决:
1. 使用 clear 属性
在浮动元素下面添加一个空元素,并设置 clear 属性为 both、left 或 right,以清除浮动,使其不再影响后面的元素,从而实现换行的效果。
```html
<div class="floats">
<div class="float">浮动元素1</div>
<div class="float">浮动元素2</div>
<div class="float">浮动元素3</div>
<div class="clear"></div>
</div>
```
```css
.floats {
width: 500px;
overflow: hidden;
}
.float {
float: left;
width: 200px;
height: 100px;
background-color: pink;
}
.clear {
clear: both;
}
```
2. 使用 display 属性
将浮动元素的父元素的 display 属性设置为 inline-block 或 table,让其具有包裹性,从而实现浮动元素换行的效果。
```html
<div class="floats">
<div class="float">浮动元素1</div>
<div class="float">浮动元素2</div>
<div class="float">浮动元素3</div>
</div>
```
```css
.floats {
width: 500px;
display: inline-block;
}
.float {
float: left;
width: 200px;
height: 100px;
background-color: pink;
}
```
3. 使用 flex 布局
将浮动元素的父元素的 display 属性设置为 flex,使用 flex-wrap 属性控制是否换行,从而实现浮动元素换行的效果。
```html
<div class="floats">
<div class="float">浮动元素1</div>
<div class="float">浮动元素2</div>
<div class="float">浮动元素3</div>
</div>
```
```css
.floats {
display: flex;
flex-wrap: wrap;
width: 500px;
}
.float {
width: 200px;
height: 100px;
background-color: pink;
}
```