html元素居中

2018-08-15  本文已影响10人  Macgx

一、不定宽高元素居中

  1. table
HTML:
<div class="father">
    <div class="son">
        this is content
    </div>
</div>

CSS:
.father {
    display: table;
}

.son {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
  1. absolute, transform
HTML:
<div class="father">
    <div class="son">
        is this OK?
    </div>
</div>

CSS:
.father {
    position: relative;
}

.son {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
  1. css3 flex
HTML:
<div class="container">
    <div class="inner">
        this is a box fixed in center of screen<br>The second line
    </div>
</div>

CSS:
.father{
    display: flex;
    align-items: center;
    justify-content: center;
}
  1. :before和display:inline-block
HTML:
<div class="father">
    <div class="son">
        this is a box fixed in center of screen<br>The second line
    </div>
</div>

CSS:
.father {
    text-align: center;
    background-color: red;
}

.father:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

.son {
    display: inline-block;
}
  1. vw vh和translate
HTML:
<div class="inner">
    this is a box fixed in center of screen
</div>
CSS:
.inner {
   position:fixed;
   top: 50vh;
   left: 50vw;
   transform: translate(-50%, -50%); 
}

二、固定宽高元素居中

  1. fixed
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 800px;
height: 400px;
  1. absolute
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 300px;
height: 350px;
上一篇 下一篇

猜你喜欢

热点阅读