CSS: vertical alignment

How to align vertically without using display table / table or absolute position?

#parent {
  border: 1px solid red;
  height: 100vh;
}

.child {
  border: 1px solid blue;
}
<div id="parent">
  <div class="child">
    <p>I want to be vertical aligned</p>
  </div>
</div>
Run code
+4
source share
7 answers

Here is another option using the Flex property.

<div id="parent">
  <div class="child">
    <p>I want to be vertical aligned</p>
  </div>
</div>

#parent {
  border: 1px solid red;
  display: flex;
  align-items: center;
  height: 100vh;
}

.child {
  border: 1px solid blue;
  flex-grow: 1;
}

Codepen Demo Link

+3
source

You can use a relative position, with a top of 50% and a translation of -50%.

#parent {
  border: 1px solid red;
  height: 100vh;
}

.child {
  position: relative;
  top: 50%;
  transform: translate(0,-50%);
  border: 1px solid blue;
}
<div id="parent">
  <div class="child">
    <p>I want to be vertical aligned</p>
  </div>
</div>
Run code
+3
source

floater div

#parent {
  border: 1px solid red;
  height: 100vh;
}
.floater {
    float:left;
    height:50%;
    width:100%;
    margin-bottom: -25px;
}
.child {
  border: 1px solid blue;
  clear: both;
  height:50px;
}
<div id="parent">
  <div class="floater"></div>
  <div class="child">
    <p>I want to be vertical aligned</p>
  </div>
</div>
+1

display: flex.
CSS

#parent {
  border: 1px solid red;
  height: 100vh;
  display: flex;
  align-items: center;     /* vertical */
  justify-content: center; /* horizontal */
}

.child {
  border: 1px solid blue;
}
<div id="parent">
  <div class="child">
    <p>I want to be vertical aligned</p>
  </div>
</div>
+1

display:flex;:

#parent {
  border: 1px solid red;
  height: 100vh;
  display:flex;
  align-items:center;
  justify-content:center;
}
0

, ,

position: fixed; top: 50%;
0

, flex - . @rblarsen, @Satheesh Kumars.

, , : IE9 + FF Chrome ...

check this script: https://jsfiddle.net/kLLz0nm2/

HTML

<div class="wrapper">
   <div class="content">Middle aligned</div>
   <div class="middle"></div>
</div>

CSS

.wrapper{
   width : 100%;
   height : 100%;
   text-align: center;
}

.content{
   display: inline-block;
   vertical-align: middle;
}

.middle{
   height: 100%;
   display: inline-block;
   vertical-align: middle;
}

PS - the above solution translatewhile quite simple can sometimes cause problems with poor processing, check: the correct version looks sharper

0
source

Source: https://habr.com/ru/post/1685884/


All Articles