CSS实现两个盒子居中上下间距的方法非常简单,我们可以采用margin和属性进行设置。下面给大家介绍两种实现方法。方法一:.boxwrapper { : relative; height: 300px...
CSS实现两个盒子居中上下间距的方法非常简单,我们可以采用margin和position属性进行设置。下面给大家介绍两种实现方法。
方法一:
.box-wrapper {
position: relative;
height: 300px;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
margin-top: 20px;
} 这种方法需要使用定位属性position和transform来实现居中,它的优点是能够根据父容器的高度进行自适应。
方法二:
.box-wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 300px;
}
.box {
margin-top: 20px;
} 这种方法使用了CSS3中的Flex布局,它的优点是代码简单易懂,但需要考虑到浏览器的兼容性。
无论使用哪种方法,我们都可以通过调节margin-top的值来控制两个盒子之间的间距。