Search code examples
htmlcssalignmentcenter

How do I line these two divs up vertically?


I have the following HTML markup:

<div id="pageWrapper">
  <div style="display: block; float: left; clear: left; border: 1px solid green;">
    <div style="display: inline-block; margin-top: 0; padding-top: 0; border: 1px solid red;">
      <img src="http://i.imgur.com/5OluoVs.png" height="95" width="75" /> <!-- some random image from imgur for test purposes -->
    </div>

    <div style="display: inline-block; border: 1px solid blue;">
      <h4>Main Object</h4>
      <p style="margin: 0; padding: 0;">
        Attribute 1
      </p>
      <p style="margin: 0; padding: 0;">
        Attribute 2
      </p>
      <p style="margin: 0; padding: 0;">
        Attribute 3
      </p>
    </div>    
  </div>

https://jsfiddle.net/34xfgx5b/

You'll see that there are 3 divs with borders. The green border contains two sub divs. One of these divs had a red border, and the other has a blue border.

I'm trying to figure out how to get these two divs to both be center aligned vertically inside the green box, such that the image is vertically in the center and the text appears vertically in the center as well. Right now, they're both stuck to the bottom, and furthermore, the text within the blue div is smashed to the bottom. Whenever I try to adjust the margins of the inner boxes, it messes up the formatting of the green box.

I've been trying to use vertical-align: middle to achieve this, but I can't get it to work for me.

How do I get these two inner divs vertically centered inside of the green box, as well as get the text centered vertically within the blue box? If possible, I'd like to try to keep all of the styling inside the HTML because in the real implementation this needs to be one file.


Solution

  • Use Flexbox :)

    I tidied up your code to split classes out:

    Your HTML:

    <div id="pageWrapper">
      <div class="green">
        <div class="red">
          <img src="http://i.imgur.com/5OluoVs.png" height="95" width="75" /> <!-- some random image from imgur for test purposes -->
        </div>
    
        <div class="blue">
            <h4 class="title">Main Object</h4>
            <p class="pg">
              Attribute 1
            </p>
            <p class="pg">
              Attribute 2
            </p>
            <p class="pg">
              Attribute 3
            </p>
        </div>    
      </div>
    </div>
    

    Your CSS:

    .green {
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px 
      solid green;
    }
    
    .red {
      border: 1px solid red;
    }
    
    .blue {
      border: 1px solid blue;
    }
    
    .title {
      margin: 0;
    }
    
    .pg {
      margin: 0; 
      padding: 0;
    }
    

    If you use the class title, which removes your H4 margin, then you will see that your text is also centered using flexbox.