上下两个盒子垂直对齐是网页设计中经常会遇到的问题。在CSS中,我们可以使用flexbox和grid等布局技术来解决这个问题。 使用Flexbox Flexbox是一个基于盒子模型的布局模式,可以轻松地...
上下两个盒子垂直对齐是网页设计中经常会遇到的问题。在CSS中,我们可以使用flexbox和grid等布局技术来解决这个问题。
使用Flexbox
Flexbox是一个基于盒子模型的布局模式,可以轻松地在一个容器中对齐和排列元素。要使用Flexbox来垂直对齐两个盒子,可以将它们都放到一个容器中,然后使用align-items属性来指定垂直对齐方式。
下面是一个示例代码:
.container {
display: flex;
align-items: center;
justify-content: center;
height: 500px;
}
<br>
.box1 {
background-color: #ffa500;
width: 200px;
height: 100px;
}
<br>
.box2 {
background-color: #87ceeb;
width: 200px;
height: 200px;
} .container {
display: grid;
grid-template-rows: 1fr auto 1fr;
height: 500px;
}
<br>
.box1 {
background-color: #ffa500;
width: 200px;
height: 100px;
justify-self: center;
align-self: end;
}
<br>
.box2 {
background-color: #87ceeb;
width: 200px;
height: 200px;
justify-self: center;
align-self: start;
}