面试题之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;
}

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

发布了6 篇原创文章 · 获赞 24 · 访问量 269

猜你喜欢

转载自blog.csdn.net/ephemeral0/article/details/104644932