怎么操作两个div垂直上下分布
时间: 2024-10-24 14:14:14 浏览: 16
如果你想让两个`<div>`元素在页面上垂直堆叠,你可以通过CSS的布局属性来实现,例如Flexbox或Grid布局,或者传统的浮动和定位。这里有几个简单的例子:
1. **Flexbox**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
display: flex;
align-items: center; /* 垂直居中 */
}
.div1, .div2 {
width: 100px;
height: 100px;
background-color: #f00; /* 红色示例 */
margin: 5px;
}
</style>
</head>
<body>
<div class="container">
<div class="div1"></div>
<div class="div2"></div>
</div>
</body>
</html>
```
2. **Grid** (如果浏览器支持):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
display: grid;
place-items: center; /* 垂直中心对齐 */
grid-template-columns: auto auto; /* 自动分配宽度 */
gap: 5px;
}
.div1, .div2 {
background-color: #f00;
height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="div1">Div1</div>
<div class="div2">Div2</div>
</div>
</body>
</html>
```
3. **绝对定位+相对父元素**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.parent {
position: relative;
}
.child {
position: absolute;
top: 0; bottom: 0; /* 高度自适应 */
}
</style>
</head>
<body>
<div class="parent">
<div class="child div1" style="width: 100px; height: 100px; background-color: red;"></div>
<div class="child div2" style="width: 100px; height: 100px; background-color: blue;"></div>
</div>
</body>
</html>
```
阅读全文