CSS水平居中与垂直居中的总结

CSS实现居中的方法着实不少,在工作中也比较容易实现,本文旨在归纳各种居中的方法,对各种方法有比较清晰的认识,达到在实际工作中 “ 对方抓药 ” 的目的。

工作中有时水平居中、垂直居中会同时实现,本次分开介绍。

水平居中

  • 行内元素水平居中

  1. 给其父元素设置: text-align:center

这里指的是在行内元素不转化为块级元素的情况下,查了好多资料都是这一种方法,不过确实好用,这里父元素应为块级元素。
注意:

  • 使用display、position行内元素特性会发生改变(虽然position设置relative没有改变行内元素特性,但是行内元素宽度不确定,也不能准确实现居中)
  • transform只适用与块级元素
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .d1 {
      width: 150px;
      height: 150px;
      background: yellow;
      text-align: center
    }
    span {
      background: blue;    
    }
  </style>
</head>
<body>
  <div class="d1">     //块级元素
    <span>hello</span>     //行内元素
  </div>
</body>
</html>
测试01.PNG
  • 块级素水平居中

1.设置 margin: 0 auto;

  • 仅适用于块级元素(block),不适用于行内块元素(inline-block)。
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .d1 {
      width: 250px;
      height: 150px;
      background: yellow;
    }
    span {
      width:100px;
      background: blue;
      margin: 0 auto;
      display:block;     //改为inline-block居中失效
    }
  </style>
</head>
<body>
  <div class="d1">
      <span>
        hello
      </span>
  </div>
</body>
</html>

测试02.PNG

2.margin: 0 auto;结合position。

必须设置 left: 0; right: 0;

  • 对于块级元素(block)直接margin: 0 auto;就搞定了,当position同时也进行了设置时,块级元素(block)和行内块(inline-block)水平居中都能实现。
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .d1 {
      width: 250px;
      height: 150px;
      background: yellow;
      position: relative;
    }
    span {
      width:100px;
      background: blue;
      position: absolute;
      top:0;
      left:0;
      right:0;
      margin: 0 auto;
      /* display: inline-block; */   //设置了position: absolute,默认具有了行内块特性
    }
  </style>
</head>
<body>
  <div class="d1">
      <span>
        hello
      </span>
  </div>
</body>
</html>

测试03.PNG

3.transform结合position。

原理是利用positon移动元素左上角至父元素水平中间位置,再利用transform把元素水平中心和父元素水平中心对齐,因为两者百分比参考对象不同,所以必须两次操作。

  • 这里适用块级元素(block)和行内块(inline-block),不需要知道快读,若已知宽度也可用其他方法。
  • 这里 position 不能设置 relative,虽然它对行内元素有效,但会导致transform 失效。
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .d1 {
      width: 250px;
      height: 150px;
      background: yellow;
      position: relative;
    }
    span {
      background: blue;
      position: absolute;
      left:50%;    //百分比相对于父元素
      transform: translateX(-50%);    //百分比相对于自身
    }
  </style>
</head>
<body>
  <div class="d1">
      <span>
        hello world
      </span>
  </div>
</body>
</html>

测试04.PNG

4.display:flex/inline-flex

将父元素设置为弹性伸缩盒,通过设置子元素的排列实现水平居中。

  • justify-content 设置子元素在主轴方向上中间对齐,实现水平居中。
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .d1 {
      width: 250px;
      height: 150px;
      background: yellow;
      display: flex;
      justify-content: center;
    }
    span {
      background: blue;
      height: 50px;
    }
  </style>
</head>
<body>
  <div class="d1">
      <span>
        hello world
      </span>
  </div>
</body>
</html>
测试05.png
  • 也可以用flex-direction改变主轴方向,然后用align-items或者align-self在侧轴上居中,效果一样。
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .d1 {
      width: 250px;
      height: 150px;
      background: yellow;
      display: flex;
      flex-direction: column;
      align-items:center;
    }
    span {
      background: blue;
      width:100px;
      height: 50px;
    }
  </style>
</head>
<body>
  <div class="d1">
      <span>
        hello world
      </span>
  </div>
</body>
</html>

测试06.png

5.若width固定,使用绝对定位方式, 以及负值的margin-left

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .d1 {
      width: 250px;
      height: 150px;
      background: yellow;
      position: relative;
    }
    span {
      background: blue;
      width:100px;
      position: absolute;
      left: 50%;
      margin-left: -50px;
    }
  </style>
</head>
<body>
  <div class="d1">
      <span>
        hello world
      </span>
  </div>
</body>
</html>

测试07.png

6.不推荐
若子元素包含 float:left 属性, 为了让子元素水平居中, 则可让父元素宽度设置为fit-content,并且配合margin, 作如下设置:

.parent{
    width: -moz-fit-content;
    width: -webkit-fit-content;
    width:fit-content;
    margin:0 auto;
}
//fit-content是CSS3中给width属性新加的一个属性值,它配合margin可以轻松实现水平居中,
 目前只支持Chrome 和 Firefox浏览器.

垂直居中

  • 行内元素垂直居中

单行文本垂直居中,通过设置行高为父元素高度(父元素高度已知)。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    div {
      background: yellow;
      width: 300px;
      height: 200px;
    }
    span {
      background: blue;
      line-height: 200px;
    }
  </style>
<body>
  <div>
    <span>hello world</span>
  </div>
</body>
</html>
测试08.png

图片垂直居中,设置上下padding(父元素高估不设置)。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    p {
      border: 1px solid;
      
    }
    img {
      height: 100px;
      vertical-align: middle;   //不加这个上下会有偏差
      padding:20px 0;
    }
  </style>
<body>
  <p>
    ![](http://upload-images.jianshu.io/upload_images/6828981-5e462e315494397c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  </p>
</body>
</html>
测试09.png

图片垂直居中,下边这种方法会有一定偏差(父元素高估不设置)。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    p {
            border: 10px solid black;
            line-height: 210px;
            text-align: center;
        }

        img {
            height: 200px;
            vertical-align: middle;
        }
  </style>
<body>
  <p>
    ![](http://upload-images.jianshu.io/upload_images/6828981-5e462e315494397c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  </p>
</body>
</html>
测试10.png

图片垂直居中,图片作为背景。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    p {
        height: 300px;
        width: 300px;
        border: 1px solid;
        padding:20px;
        }

    img {
          width:100%; 
          height: 100%;
          display:block;
          background:url('https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2206324925,1265061622&fm=200&gp=0.jpg') no-repeat;
          background-size:cover;
        }
  </style>
<body>
  <p>
    <img src="" alt="">
  </p>
</body>
</html>
测试11.png
  • 块级元素垂直居中

1. 若元素是行内块级元素, 基本思想是使用display: inline-block, vertical-align: middle和一个伪元素让内容块处于容器中央。
行内元素可可以转换为inline-block实现居中。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    p {
        height: 200px;
        width: 300px;
        border: 1px solid;
        }

    p::after,img {
          width:100px; 
          display:inline-block;
          vertical-align: middle;
        }
    p::after {
      content: '';
      height: 100%;
    }
  </style>
<body>
  <p>
    ![](http://upload-images.jianshu.io/upload_images/6828981-5e462e315494397c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  </p>
</body>
</html>

测试12.png

2.用 vertical-align 属性

vertical-align只有在父层为 td 或者 th 时, 才会生效, 对于其他块级元素, 例如 div、p 等, 默认情况是不支持的. 为了使用vertical-align, 我们需要设置父元素display:table, 子元素 display:table-cell;vertical-align:middle;

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    .container {
        display: table;
        height: 200px;
        width: 300px;
        border: 1px solid #000;
        }

    span {
        display: table-cell;
        height:100px;
        vertical-align: middle;
          
        }
  </style>
<body>
  <div class="container">
    <span>hello</span>
  </div>
</body>
</html>

测试13.png

3.使用弹性盒子,设置子元素在侧轴或主轴的排列

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    p { 
        display:flex;
        /* align-items: center; */
        height: 200px;
        width: 300px;
        border: 1px solid;
        }

    img {
        width:100px; 
        display:inline-block;
        align-self:center;
        }
  </style>
<body>
  <p>
    ![](http://upload-images.jianshu.io/upload_images/6828981-5e462e315494397c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  </p>
</body>
</html>

测试14.png

4.transform+position

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    p { position: relative;
        height: 200px;
        width: 300px;
        border: 1px solid;
        }

    img {
        position: absolute;
        top:50%;
        transform: translateY(-50%);
        width:100px; 
        display:block;
        }
  </style>
<body>
  <p>
    ![](http://upload-images.jianshu.io/upload_images/6828981-5e462e315494397c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  </p>
</body>
</html>

测试15.png

5.position+margin

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    p { 
        position: relative;
        height: 200px;
        width: 300px;
        border: 1px solid;
        }

    img {
        display:inline-block;
        height:100px;
        position: absolute;
        top:50%;
        margin-top:-50px; 
        }
  </style>
<body>
  <p>
    ![](http://upload-images.jianshu.io/upload_images/6828981-5e462e315494397c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  </p>
</body>
</html>

测试16.png

6.margin: auto 0;结合position。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
  <style>
    p { 
        position: relative;
        height: 200px;
        width: 300px;
        border: 1px solid;
        }

    img {
        display:inline-block;
        height:100px;
        position: absolute;
        top:0;
        bottom:0;
        margin: auto 0;
        }
  </style>
<body>
  <p>
    ![](http://upload-images.jianshu.io/upload_images/6828981-5e462e315494397c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  </p>
</body>
</html>
测试17.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容