css中怎样让盒子居中

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

在CSS中,让盒子居中一直是一个普遍的问题。以下是一些方法。/* 1.使用margin属性 */ .box { width: 100px; height: 100px; background-colo

在CSS中,让盒子居中一直是一个普遍的问题。以下是一些方法。

/* 1.使用margin属性 */
.box {
  width: 100px;
  height: 100px;
  background-color: gray;
  margin: 0 auto;
}

/* 2.使用display属性 */
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

.parent .box {
  width: 100px;
  height: 100px;
  background-color: gray;
}

/* 3.使用position属性 */
.parent {
  position: relative;
}

.parent .box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
} 

以上是几种让盒子居中的方法。使用margin、display和position属性都可以实现这个目标。

文章说明:

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

题图来自Unsplash,基于CC0协议

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

评论列表 评论
发布评论

评论: css中怎样让盒子居中

粉丝

0

关注

0

收藏

0

已有0次打赏