当前位置:首页 > IT技术 > Web编程 > 正文

css居中(上下左右居中,垂直居中,水平居中)
2021-10-11 14:56:32

初始样式

已知子盒子宽高

.outside {
  width: 200px;
  height: 200px;
  background-color: red;
}

.inside {
  width: 100px;
  height: 100px;
  background-color: rgb(231, 255, 15);
}

<div class="outside">
  <div class="inside">
    我是被居中的盒子
  </div>
</div>

上下左右居中

在初始的样式上添加以下样式
方式一:position+margin+top/bottom/left/right
必须有父盒子与子盒子的宽高

.outside{
  position:relative;
}

.inside {
  position:absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

方式二:position+top/left

.outside{
  position:relative;
}

.inside {
  position:absolute;
  /*50px:(父-子)/2*/
  top: 50px; 
  left: 50px;
}

方式三:position+margin-top/margin-left

.outside{
  position:relative;
}

.inside {
  position:absolute;
  /*50px:(父-子)/2*/
  margin-top: 50px; 
  margin-left: 50px; 
}

方式四:display:table-cell

.outside{
  display:table-cell;
  vertial-align:middle;
  text-align: center;
}

.inside {
  display: inline-block;
}

方式五:position+top:calc
可以未知父盒子的宽度
top与left还可以用calc计算,calc()中的运算符左右都需要空格,50px是inside盒子长度的一半

.outside{
  position:relative;
}

.inside {
  position:absolute;
  /*50%:相对于父盒子的宽度;50px:子盒子的宽度的一半*/
  top: calc(50% - 50px); 
  left: calc(50% - 50px); 
}

方式六:position+top/left+transform
未知子盒子宽高

.outside{
  position:relative;
}

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

方式七:display:flex
未知子盒子宽高

.outside{
  display:flex;
  justify-content: center;
  align-items: center;
}

左右居中

在初始的样式上添加以下样式

.inside{
  margin: 0 auto;
}

上下居中

在初始的样式上添加以下样式

.outside{
  display: table-cell;
  vertical-align: middle;
}

行内元素垂直水平居中

初始样式

<h1 class="text">line-height和height的使用</h1>

.text{
  height: 100px;
  background-color: chartreuse;
}

在初始的样式上添加以下样式

.text{
  /* 垂直居中,line-height与height值一致 */
  line-height: 100px;
  /* 水平居中 */
  text-align: center;
}

本文摘自 :https://www.cnblogs.com/