0

I have 2 div's

<div class="outerDiv">
   <div class="innerDiv">
        Hi i am trying to align center vertically and horizontally 
   </div>
<div>  

How do I centre the two divs (Outer and Inner) ?

Question
  • 57
  • 3
  • 11

3 Answers3

1

Try this.

I added an outer wrapper to the 2 divs, added margins and changed the position type. Run the snippet.

.outerWrapper {
 position:absolute;
 left:50%;
 top:50%;
 margin:-75px 0 0 -135px;
}
<div class="outerWrapper">
    <div class="outerDiv">
        <div class="innerDiv">Hi i am trying to align center vertically and horizontally
        </div>
    <div>
</div>

EDIT:

You can apply the CSS to the outerDiv and get rid of the outerWrapper but I'd recommend staying with the outerWrapper so that you can still change the margins in the inner and outer Divs.

Blake
  • 84
  • 12
1

One method of centring elements with an unknown width on the page is to use the CSS flexbox functionality.

You need to give the outer element the following CSS properties:

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

This will center align the inner element in the outer element.

The justify-content: center; property aligns the child elements along the main axis, in this example the horizontal one. The align-items: center; property does the cross axis, the vertical one.

Please note that you may require vendor prefixing to fully support all browsers. (Note: this example uses the new specification).

For a JSFiddle example, please see this example that I have quickly created for you.

Rob Farr
  • 853
  • 1
  • 9
  • 17
0

this will work fine

.outerDiv {
  position: fixed;
  width: 100%;
  height: 100%;
}
.innerDiv {
  text-align: center;
  margin: auto;
  top: 40%;
  position: relative;
}

<div class="outerDiv">
   <div class="innerDiv">
        Hi i am trying to align center vertically and horizontally 
   </div>
<div> 
Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
  • Hi @Muhammad, Is there any possible situation with out using Width and Height property to align center Vertically and Horizontally? can you please give me any solution.. Thanks!!! – Question Apr 07 '15 at 09:13
  • I mean, i want center align OuterDiv also..@Muhammad – Question Apr 07 '15 at 09:14