css两个盒子居中上下间距

admin 轻心小站 关注 LV.19 运营
发表于前端技术学习版块 css,教程

CSS实现两个盒子居中上下间距的方法非常简单,我们可以采用margin和position属性进行设置。下面给大家介绍两种实现方法。方法一:.box-wrapper { position: relati

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的值来控制两个盒子之间的间距。

文章说明:

本文原创发布于探乎站长论坛,未经许可,禁止转载。

题图来自Unsplash,基于CC0协议

该文观点仅代表作者本人,探乎站长论坛平台仅提供信息存储空间服务。

评论列表 评论
发布评论

评论: css两个盒子居中上下间距

粉丝

0

关注

0

收藏

0

已有0次打赏