DIV horizontal layout and vertical centering

First, the middle level

1. inline-block + text-align

text-align (he would have inherited) acting on the block-level element, will allow block-level metadata elements of inline-block child, arranged

<div class="parent">
   <div class="child">demo</div>
</div>

  .parent{
    width: 200px;
    text-align: center;
   }
        .child{
    display: inline-block;  
   }

2. table + margin

If the table where the element is not set to its wide, his wide would be softened by the content

<div class="parent">
   <div class="child">demo</div>
</div>

  .child{
      display: table;
      margin: 0 auto;
     }

3.absolute + transform

<div class="parent">
   <div class="child">demo</div>
</div>

.parent{
    position: relative;
   }
   .child{
    position: absolute;
    left:50%;
    transform: translateX(-50%);
   }

4.flex + justify content

In fact, property values ​​flex can also support margin: 0 auto;

<div class="parent">
   <div class="child">demo</div>
</div>

.parent{
    display: flex;
    justify-content: center;
   }

 

or

.parent{
    display: flex;
   }
   .child{
    border: 1px solid green;
    margin: 0 auto;
   }

Two, parent and child elements are not set high, Vertical Centering

1.tale-cell + vertical-align

Property values ​​such tale-cell cell, it will automatically make him the center of the sub-elements

<div class="parent">
   <div class="child">demo</div>
</div>

.parent{
    display: table-cell;
    vertical-align: middle;
   }

2.absolute + transform

<div class="parent">
   <div class="child">demo</div>
</div>

.parent{
    position: relative;
   }
   .child{
    position: absolute;
    top:50%;
    transform: translateY(-50%);
   }

3.flex + align-items

align-items his default is stretched, covered the entire container

<div class="parent">
   <div class="child">demo</div>
</div>

.parent{
    display: flex;
    align-items: center;
   }

Third, the size of the container is not fixed, while the center

 

Renderings .png

1.inline-block + text-align + tale-cell + vertical-align

Property values ​​such tale-cell cell, it will automatically make him the center of the sub-elements

<div class="parent">
   <div class="child">demo</div>
</div>

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

2.absolute + transform

<div class="parent">
   <div class="child">demo</div>
</div>

.parent{
    position: relative;
   }
   .child{
    position: absolute;
    top:50%;

    left:50%;
    transform: translate(-50%,-50%);

   }

3.flex + judifycontent + align-items

align-items他的默认值是 stretch拉伸,布满整个容器

<div class="parent">
   <div class="child">demo</div>
</div>

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

Guess you like

Origin www.cnblogs.com/x-yy/p/11372357.html