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 此元素会作为块级表格来显示(类似 <table>)
display:table-cell 此元素会作为一个表格单元格显示(类似 <td> 和 <th>)


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


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

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,686评论 1 92
  • 1. 前言 前端圈有个“梗”:在面试时,问个css的position属性能刷掉一半人,其中不乏工作四五年的同学。在...
    YjWorld阅读 10,141评论 5 15
  • 移动开发基本知识点 一.使用rem作为单位 html { font-size: 100px; } @media(m...
    横冲直撞666阅读 8,893评论 0 6
  • H5移动端知识点总结 阅读目录 移动开发基本知识点 calc基本用法 box-sizing的理解及使用 理解dis...
    Mx勇阅读 10,123评论 0 26
  • 昨天的故事, 透过今早的光线, 把你的回忆收集。 那一刻, 你陷入一种回忆, 与另一个自己展开心灵的对话。
    小剧在成长阅读 1,664评论 2 6