css垂直居中(有些包含了水平居中)

html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="one"></div>
  <div class="two"></div>
  <div class="three"></div>

  <div class="four">dasdasdjka</div>
  <div class="five">I am gray</div>

  <div class="six"><div class="content"><div><div>
  <div class="seven">移动端用的比较多,无需设置宽高</div>

  <div class="eight"><div class="content">A</div></div>
</body>
</html>

css:

.one{
  position:absolute;
  width:200px;
  height:200px;
  top:50%;
  left: 50%;
  margin-top:-100px;
  margin-left: -100px;
  background:red;
}

.two {
  position: fixed;
  width:180px;
  height:180px;
  top:50%;
  left: 50%;
  margin-top:-90px;
  margin-left: -90px;
  background:orange;
}

.three {
  position: fixed;/* absolute也行 */
  width: 160px;
  height: 160px;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  background: pink;
}

.four {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  width: 140px;
  height: 140px;
  background: purple;
}

.five {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  background: gray;
}

.six {
  width:90px;
  height:90px;
  display:-webkit-box;
  -webkit-box-pack:center;
  -webkit-box-align:center;
  background:yellow;
  color:black;
}
.six .content {
  width: 50px;
  height: 50px;
  background: green;
}

/* 好处是无需设置宽高,移动端用的比较多 */
.seven {
  position:absolute;
  width: 120px;
  height: 120px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: blue;
}

.eight {
  position: fixed; /* absolute */
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  text-align: center;
}
.eight:before {
  content: '';
  display: inline-block;
  vertical-align:middle;
  height: 100%;
}
.eight .content {
  display:inline-block;
  vertical-align:middle;
  width: 60px;
  height: 60px;
  line-height:60px;
  color:red;
  background:yellow;
}

效果图:
这里写图片描述
作者:徐尤熙
链接:https://www.zhihu.com/question/20543196/answer/89218605
来源:知乎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值