面试题之css中的垂直水平居中

垂直水平居中

面试经常问的一个问题,今天来总结下,分两块:居中元素需要高度和不需要高度

先写下都需要的样式和标签元素

  • 需要用得到的标签元素
<div class="wrap">
    <div class="box">我是居中元素</div>
</div>
  • 给body设置宽度
html,body {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

需要高度

1、定位和负margin

.wrap {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.box {
  width: 100px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -50px;
  margin-left: -50px;
  background-color: yellowgreen;
}

2、定位和margin:auto

.wrap {
  position: relative;
  width: 100%;
  height: 100%;
}
.box {
  width: 100px;
  height: 100px;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  background-color: yellowgreen;
}

3、定位和calc

calc可获取当前窗口的大小

.wrap {
  position: relative;
  width: 100%;
  height: 100%;
}
.box {
  width: 100px;
  height: 100px;
  position: absolute;
  top: calc(50% - 50px);
  left: calc(50% - 50px);
  background-color: yellowgreen;
} 

高度可选

4、定位和transform:translate

transform的translate可根据自身的宽度和高度做出相应的布局

.wrap {
  position: relative;
  width: 100%;
  height: 100%;
}
.box {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: yellowgreen;
}

5、flex三件套

.wrap {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.box {
  background-color: yellowgreen;
}

6、flex与margin:auto

.wrap {
  width: 100%;
  height: 100%;
  display: flex;
}
.box {
  magin: auto;
  background-color: yellowgreen;
}

7、table-cell

将容器设为表格单元格,注意容器的宽高不能用百分比,容器的子元素要设为行级块元素或行级元素

.wrap {
  width: 500px;
  height: 500px;
  background-color: aliceblue;
  overflow: hidden;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.box {
  display: inline-block;
  background-color: yellowgreen;
} 

8、grid网格布局

.wrap {
  width: 100%;
  height: 100%;
  background-color: aliceblue;
  display: grid;
}
.box {
  justify-self: center;
  align-self: center;
  background-color: yellowgreen;
}  

9、line-height和text-align

容器要有不是百分比的宽高,子元素是行级块元素,

.wrap {
  width: 500px;
  height: 500px;
  background-color: aliceblue;
  text-align: center;
  line-height: 500px;
}
.box {
  display: inline;
  background-color: yellowgreen;
}

目前自己就知道这几种,后期还有在补上…

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值