0

How could I vertically center a child within a parent ?

And, the width and height of child and parent is fixed, but unknown.

How could I realize it?

<div class="parent">
   <div class="child"></div>
</div>
Joe.Herylee
  • 115
  • 1
  • 3
  • 13
  • 1
    Possible duplicate of [Vertically center div in a div with height auto](http://stackoverflow.com/questions/17326981/vertically-center-div-in-a-div-with-height-auto) – digglemister May 08 '16 at 08:24
  • Possible duplicate of [How to center an element horizontally and vertically?](http://stackoverflow.com/questions/19461521/how-to-center-an-element-horizontally-and-vertically) – TylerH May 09 '16 at 20:54

4 Answers4

1

in css vertical-align:middle is used to align a child vertically centre. But this property is applied to only those elements which havedisplay:inline-block or display:table-cell. So accordingly try to apply display property and you will get vertically centre position of your elements.

Ankit Agarwal
  • 1,350
  • 10
  • 15
1

My prefered technique for centering a box both vertically and horizontally requires two containers.


The outher container

  • should have display: table;

The inner container

  • should have display: table-cell;
  • should have vertical-align: middle;
  • should have text-align: center;

The content box

  • should have display: inline-block;
  • should re-adjust the horizontal text-alignment to eg. text-align: left; or text-align: right;, unless you want text to be centered

The elegance of this technique, is that you can add your content to the content box without worrying about its height or width!

Just add your content to the content box.

Demo

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        <p>You can put anything here</p>
        <p>Yes, really anything!</p>
     </div>
   </div>
</div>

See also this Fiddle!

John Slegers
  • 45,213
  • 22
  • 199
  • 169
0

You can center things through: margin: 0 auto;

cramopy
  • 3,459
  • 6
  • 28
  • 42
0

Try this code

body {
  margin: 0;
  padding:0;
}

.div1 {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
.div2 {
  width: 50vw;
  height: 50vh;
  background: #999;
}
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
Joe.Herylee
  • 115
  • 1
  • 3
  • 13