Search code examples
cssvertical-alignment

CSS to center vertically four divs side by side inside a wrapper div


I am writing a page to show a receipt. It has the following columns:

  • image of the product.
  • description.
  • quantity.
  • price.

I created a div for the item and four divs inside for each column. I am having trouble aligning the column divs vertically (so the description, quantity and price are centered vertically with the image).

I created a little fiddle showing where I am - https://jsfiddle.net/j1dias/hpg32x7b/

I thought I could use display:inline-block and vertical-align:center, but they don't seem to be working as I expected.

I am trying to avoid using flexbox. Also I would prefer to not have to set height.

Please see below the html and the css.

Thanks.

HTML

<div class="checkout-item">
  <div class="checkout-item-image">
    <img src="https://picsum.photos/536/354"/>
  </div>
    <div class="checkout-item-description">
      <span>Product name</span>
    <br>
        <span>Product description</span>
    </div>
    <div class="checkout-item-qty">
        <span>2</span>
    </div>
    <div class="checkout-item-total-price">
        <span>$90.00</span>
    </div>
</div>

CSS

.checkout-cart {
    background-color: yellow;
    padding: 20px;
    margin-bottom: 50px;
    font-size: 0.9em;
}

.checkout-item {
    position: relative;
    overflow: hidden;
    display: inline-block;
}

.checkout-item-image {
    width: 15%;
    float: left;
    margin-right: 50px;
    display: inline-block;
    vertical-align: middle;
}

.checkout-item-image img {
    vertical-align: middle;
    max-width: 100%;
}

.checkout-item-description {
    width: 30%;
    float: left;
    margin-right: 50px;
    display: inline-block;
    vertical-align: middle;
}

.checkout-item-qty {
    width: 5%;
    float: left;
    margin-right: 50px;
    font-size: 1.5em;
    font-weight: bold;
    text-align: center;
    display: inline-block;
    vertical-align: middle;
}

.checkout-item-total-price {
    width: 5%;
    float: left;
    font-size: 1.5em;
    font-weight: bold;
    text-align: right;
    display: inline-block;
    vertical-align: middle;
}

EDIT

I ended up following the suggestions and used flexbox. It seems that it is supported by most browsers.

I changed display:inline-block to display:flexbox.

Thank you.


Solution

  • Flexbox was designed to deal with exactly this sort of problem.

    Just change display: inline-block; on your .checkout-item to:

    display: flex;
    flex-direction: row;
    align-items: center;
    

    display: flex explanation

    flex-direction: row explanation

    align-items: center explanation

    Non-flexbox solution:

    Use display: table and display: table-cell to match column heights:

    .checkout-item {
        display: table;
    }
    
    .checkout-item > div {
      display: table-cell;
      float: none;
    }