CSS实现元素居中的五种方法

1.使用text-align水平居中

<style>.center{  text-align: center;  background: rgba(0,0,0,.5);

}.center img{  width: 33%;  height: auto;

}</style><body>

  <div class="center">

        <img src="img/img.jpg" alt="img">

    </div></body>

这个属性适合自适应居中,但必须注意的是:居中的元素必须是行内元素。

2.使用absolute定位居中

<style>.center{    position: relative;    min-height: 500px;    background: rgba(0,0,0,.5);

}.center img{    width: 200px;    height: 200px;    overflow: auto;    position: absolute;    left: 50%;    top: 50%;    margin: -100px 0 0 -100px;

}</style><body><div class="center">

        <img src="img/img.jpg" alt="img">

    </div></body>

这种 方案 有非常好的跨浏览器支持。有一个缺点就是必须显式声明外部容器元素的height

3.使用translate居中

<style>.center{    position: relative;    min-height: 500px;    background: rgba(0,0,0,.5);

}.center img{  position: absolute;  top:50%;  left:50%;  transform: translate(-50%,-50%);  -webkit-transform: translate(-50%,-50%);  width:30%;  height: auto;

}</style><body><div class="center">

        <img src="img/img.jpg" alt="img">

    </div></body>

但是有以下几种缺点:

1.CSS transform 在部分就浏览器上需要使用 前缀;

2.不支持 IE9 以下的浏览器;

3.外部容器需要设置height (或者用其他方式设置),因为不能获取 绝对定位 的内容的高度

4.如果内容包含文字,现在的浏览器合成技术会使文字模糊不清

4.使用table-cell居中

<style>.center{    display: table;    background: rgba(0,0,0,0.5);    width: 200%;    height: 200%;    text-align: center;

}.center-core{    display: table-cell;    text-align: center;    vertical-align: middle;

}</style><body><div class="center">

     <div class="center-core">

           居中     </div> </div></body>

利用的知识点:

display:table    此元素会作为块级表格来显示(类似 )

display:table-cell 此元素会作为一个表格单元格显示(类似 和 )

5.使用Flexbox居中

<style>.center{    display: flex;    justify-content: center;    background: rgba(0,0,0,.5);

}.square{    height: 200px;    width: 200px;    background: red;

}.circle{    width: 150px;    height: 150px;    background: blue;

}</style><body><div class="center">

        <div class="square"></div>

        <div class="circle"></div>

        <div class="square"></div>

    </div></body>

利用的知识点:

flex-start:弹性盒子元素将向行起始位置对齐。该行的第一个子元素的主起始位置的边界将与该行的主起始位置的边界对齐,同时所有后续的伸缩盒项目与其前一个项目对齐。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容