Search code examples
htmlcssflexboxcentering

vertical align text in two different div's inside another div


I am trying to vertical align text inside two div's. I have tried a number of solutions found here but none produce the required result.

I have crated a sjFiddle:

#outer {
  position: relative;
}

#inner1 {
  position: absolute;
  align-items: center;
  top: 10%;
  bottom: 10%;
  width: 100%;
  height: 40%;
}

#inner2 {
  position: absolute;
  align-items: center;
  top: 50%;
  bottom: 10%;
  width: 100%;
  height: 40%;
}

html,
body {
  height: 100%;
}

#outer {
  background-color: purple;
  width: 50%;
  height: 50%;
}

#inner1 {
  background-color: yellow;
}

#inner2 {
  background-color: red;
}
<div id="outer">
  <div id="inner1">
    Test text 1
  </div>
  <div id="inner2">
    Test text 1
  </div>
</div>

Can anyone see how I can do this based on the code in my fiddle. Many thanks in advance for your time.


Solution

  • Is this similar to what you are trying to achieve?

    #outer {
        height:100%;
        padding:10% 0;
        box-sizing:border-box;
    }
    
    #inner1 {
      height:50%;
      width:100%;
      display:flex;
      justify-content:center;
      align-items:center;
    }
    
    
    #inner2 {
      height:50%;
      width:100%;
      display:flex;
      justify-content:center;
      align-items:center;
    }
    
    html, body { height: 100%; }
    #outer {
        background-color: purple;
    }
    #inner1 {
        background-color: yellow;
    }
    
    #inner2 {
        background-color: red;
    }
    <div id="outer">
        <div id="inner1">
             Test text 1
         </div>
         <div id="inner2">
             Test text 1
        </div>
    </div>

    I have removed the positioning from the inner divs and made them flexboxes, thus allowing us to use justify-content and align-items to achieve horizontal and vertical centering.