Vertically center CSS rule works for row but not f

2019-02-16 00:10发布

问题:

I am trying to use the following CSS rules to vertically center aligned content in bootstrap 3 -

.center {
   display:flex;
   align-items:center !important;
   background-color:red;
   text-align:center;     
}

@media ( min-width:768px ) {
  .center {
     display:flex;
     align-items:center !important;
     background-color:red;
     text-align:center;     
   }
}

@media ( min-width: 992px ) {
  .center {
   display:flex;
   align-items:center !important;
   background-color:red;
   text-align:center;     
  }
}
@media ( min-width: 1200px ) {
.center {
    display:flex;
    align-items:center !important;
    background-color:red;
    text-align:center;     
  }
}

And, here is my html

<div class="row center"> <!--if .center is here valign works-->
  <div class="col-sm-4"> <!--if .center is here valign doesn't work-->
     test
  </div>    
<div class="col-sm-8 ">
  test </br>
  test </br>
  test </br>
</div>    

You can find it in codepen.io.

Any help?

回答1:

You can do this in two ways.

  1. Using Absolute position

  2. Using display:table

USING ABSOLUTE POSITION

DESC: Give parent element {{position:relative}} and child(element to be centered) as

{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
   -moz-transform: translateY(-50%);
}

USING TABLE BLOCK

DESC: Give parent element as display:table;width:100% and second parent as display:table-cell;vertical-align:middle;

Note*: {table-row} should have some height greater than its content.