CSS level achieved in several ways centered vertically

 

<div class="box">
    <div class="sub size">123123</div>
</div>

css:

.box {
    border: 1px solid red;
    width: 300px;
    height: 300px;
}

.sub{
    background: green;    
}

.sub.size{
    width: 100px;
    height: 100px;
}

A: absolute + negative margin

  Child element needs of a given width and height, with respect to the width and height of the parent element

.box {
    position: relative;
}
.sub {
    position: absolute;;
    top: 50%;
    left: 50%;    
    margin-top: -50px;
    margin-left: -50px;
}

二、absolute + margin auto

  By setting the distance in all directions is 0, then the margin is set to auto, it may be centered in the respective directions. Child element set width and height required.

.box {
    position: relative;
}
.sub {
    position: absolute;;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

三、absolute + transform

  Sub-element does not need a fixed width and height

 

.box {
    position: relative;
}
.sub {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

 

Four, css-table

  The new css table attributes, let us turn ordinary elements into a table element of reality effect, this feature can also be achieved through horizontal and vertical centering

.box {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.sub {
    display: inline-block;
}

Five: flex

.box {
    display: flex;
    justify-content: center;
    align-items: center;
}

 

Guess you like

Origin www.cnblogs.com/Lyui/p/11535870.html