Advaith
Advaith

Reputation: 2590

After aligning a div horizontally and vertically center

I saw a lot of question How to align a div horizontally and vertically center and i got a answer also.

The code which i got: Html-

<div class="outer">
   <div class="middle">
      <div class="inner">
         <div align="center">
            <h1>The Content</h1>

            <p>Once upon a midnight dreary...</p>
         </div>
      </div>
   </div>
</div>

Css-

.outer {
   display: table;
   position: absolute;
   height: 100%;
   width: 100%;
}

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

.inner {
   margin-left: auto;
   margin-right: auto;
   background: blue; /*gave blue to know the height and width*/ 
}

And i got it correctly.
But i am not able to give a default height to it.

When i give width: 50%; and height: 50%; to class="inner" only the width is being accepted.
I am not even able to give padding space between top and bottom.
Please help.
Please don't give me another code to align a div vertically and horizontally center

Upvotes: 0

Views: 425

Answers (2)

John Slegers
John Slegers

Reputation: 47101

What (I think) you want, is this :

body {
    margin : 0;
}

.outer {
   display: table;
   position: absolute;
   height: 100%;
   width: 100%;
}

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

.inner {
   display: inline-block;
   width: 50%;
   height: 50%;
   background: blue;
}
<div class="outer">
   <div class="middle">
      <div class="inner">
          <h1>The Content</h1>
          <p>Once upon a midnight dreary...</p>
      </div>
   </div>
</div>

See also this Fiddle!

Upvotes: 1

BigRedDog
BigRedDog

Reputation: 928

You are not assigning height: 50% in the right place.

The 50% is taking half of inner div. What you need to do is to assign for the div inside of class 'inner'.

You can try flex box.

Add this code:

.inner {
   margin-left: auto;
   margin-right: auto;
   background: blue;
   height: 50%; 
   width:50%;
    display: flex;
  flex-direction: column;
  justify-content: center;
}

Check it out at https://jsfiddle.net/ke5z9ukh/1/

Upvotes: 0

Related Questions