lycorisradiata

css水平垂直居中的几种方法
一、脱离文档流元素的居中1.margin:auto法html代码: <div class="de...
扫描右侧二维码阅读全文
16
2018/10

css水平垂直居中的几种方法

一、脱离文档流元素的居中

1.margin:auto法

html代码:

  <div class="demo1">
     <image src="1.png">
  </div>

css代码:

     .demo1{
          width: 420px;
          height: 284px;
          position: relative;
          border: 1px solid #465468;
     }
    .demo1 img{
          position: absolute;
          margin: auto;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
     }

效果如图:
12.png

2.负margin法

html代码:

   <div class="demo2">
      <div class="inner"></div>
    </div>

css代码:

   .demo2{
          width: 420px;
          height: 284px;
          border: 2px solid #181716;
          position: relative;
     }
     .demo2 .inner{
          width: 400px;
          height: 264px;
          background-color: #ffa516;
          position: absolute;
          top: 50%;
          left: 50%;
          margin-top: -132px; /*height的一半*/
          margin-left: -200px; /*width的一半*/
     }

效果如图:
22.png


二、未脱离文档流元素的居中

1.display: table-cell

html代码:

   <div class="demo3">
     <image src="2.png">
   </div>

css代码:

   .demo3{
        width: 420px;
        height: 284px;
        border: 1px solid #151101;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
    .demo3 img{
        vertical-align: middle;
    }

效果如图:
23.png

2.弹性盒子法

  <div class="demo4">
     <div class="inner"></div>
  </div>

css代码:

.demo4{
          width: 420px;
          height: 284px;
          border: 2px solid #1a0517;
          display: -webkit-flex;
          display: flex;
          -webkit-align-items: center;
          align-items: center;
          -webkit-justify-content: center;
          justify-content: center;
     }
     .demo4 .inner{
          border: 2px solid #ca0dad;
          padding: 20px;
     }

效果如图:
24.png

Last modification:December 11th, 2018 at 02:50 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment