CSS 里5种居中的方法

html:

<!DOCTYPE html>
<html>
<head>
  <title>CSS 居中</title>
</head>
<body>
  <div class="container">
    <div class="box"></div>
  </div>
</body>
</html>

css:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  height: 100vh;
}

.box {
  width: 20px;
  height: 20px;
  background-color: lightblue;
}

方法一:使用 flex 布局

.container 添加以下 css

display: flex;
justify-content: center;
align-items: center;

方法二:使用 grid 布局

.container 添加以下 css

display: grid;
justify-content: center; /* can be replaced by justify-items */
align-items: center; /* can be replaced by align-content */

方法三:使用 position 属性

.container 添加以下 css

position: relative;

.box 添加以下 css

position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);

方法四:使用 margin 属性

.container 添加以下 css

display: flex;

.box 添加以下 css

margin: auto auto;

方法五:使用 ::before 元素

.container 添加以下 css

text-align: center;

.container 元素的开始位置添加一个 ::before inline 元素,其中 margin-right: -.25em; 是为了抵消 ::before 产生的空格

.container::before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -.25em; /* mitigate the spawned single blank space */
}

.box 添加以下 css

display: inline-block;
vertical-align: middle;

注意纵向居中需要 .container 元素里的 height 类型为 <length> (a definite length).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值