css的几种居中方式

知识点

  1. 绝对定位position+margin计算偏移量
  2. transform自动计算偏移量
  3. margin:auto
  4. text-algin、vertical-algin作用于行内元素

水平居中

1、固定宽度+margin:auto

html:

  <div id="test1P">
      <div class="test1">
        水平居中,固定width,margin设置为auto,相对于父类水平居中
      </div>
    </div>

复制代码

css:

 .test1 {
        width: 200px;
        margin: auto;
        background-color: cadetblue;
      }
  #test1P {
    background-color: chartreuse;
  }
复制代码

效果:

image.png

2、text-algin+ display:inline-block(子元素)

html:

 <div id="test2P">
      <span class="test2">
        用text-align:center水平居中,在父元素使用该属性控制子元素居中,
        子元素设置成inline-block
  </span>
</div>
复制代码

css:

#test2P {
        background-color: cadetblue;
        text-align: center;
      }
.test2 {
        background-color: chartreuse;
        display: inline-block;
        width: 200px;
        }
复制代码

效果:

image.png

【小结】:
display也可以不用设置成inline-block,text-algin对inline元素也会有作用,但是设置的width就会无效。不加display属性后的效果:

image.png

垂直水平居中

1、固定宽高+绝对定位position+偏移量计算

html:

<div id="test4P">
  <div class="test4">子元素position:absolute,父元素高度确定</div>
</div>
复制代码

css:

#test4P {
        height: 150px;
        background-color: chartreuse;
        position: relative;
}
.test4 {
        position: absolute;
        width: 200px;
        height: 100px;
        background-color: cadetblue;
        top: 50%;
        left: 50%;
        margin-top: -50px;
        margin-left: -100px;
       }
复制代码

效果:

image.png

2、同上,只不过相对于自身的偏移量使用transform来计算

html:

<div id="test5P">
  <div class="test5">
    未知容器宽高,使用transform的translation做偏移,
    子元素position:absolute,jhkkkbjjhffgfsrhsts
  </div>
</div>

复制代码

css:

#test5P {
        background-color: cadetblue;
        position: relative;
        height: 300px;
      }
.test5 {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: chartreuse;
       }
复制代码

效果:

image.png

【小结】知道宽高也可以使用,transform来调整自身的偏移量,而且比使用margin更方便。

3、 vertical-align+inline-block+text-algin

html:

 <div id="test6P">
  <div class="test6">
    用vertical-align做垂直居中,父元素的伪元素高度设置为100%
  </div>
 </div>
复制代码

css:

#test6P {
        height: 200px;
        text-align: center;
        background-color: chartreuse;
  }
  #test6P::before {
    content: "";
    height: 200px;
    display: inline-block;
    vertical-align: middle;
  }
  .test6 {
    width: 250px;
    height: 150px;
    display: inline-block;
    background-color: cadetblue;
    vertical-align: middle;
  }
复制代码

效果:

image.png

【小结】vertical-algin 只对行内元素起作用,在垂直方向做对齐方式,text-algin作用于水平方向,两者加起来,即可实现水平垂直居中。

总结

对于居中布局还可以使用flex布局或者grid布局来实现,在实现中都会用到justyfy-content和algin-items这两个属性。具体的实现可以了解下flex和grid的使用。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享