Acla Acla - 2 months ago 11
CSS Question

css - how to get (responsive) li's with the same height when they have a different width?

This is my current scenario:


  • I have a row with 4 li elements and each has a bootstrap 'col-xs-3'
    class so that each element occupies the same space within that row

  • I also gave the elements 5px padding on each side

  • I removed the left padding of the first li and the right padding of the last li

  • All li's contain one image and all images have the same size (width: 800, height: 600)



The problem:


  • Due to the padding difference, li 2 and li 3 (which have more
    padding), become wider and therefore, they get a different height,
    which is visible when you look at the images



enter image description here

Is there a way to have responsive li's (and images) with the same height when there's this width difference? Thanks in advance!

HTML:

<div id="other-posts-container" class="col-xs-12 no-padding">
<h3 class="title col-xs-12 no-padding">Title here</h3>
<ul id="dont-miss-posts" class="col-xs-12">
<div class="row">
<li class="col-xs-3 no-padding">
<a href="#">
<img src="img/post-1.png">
<p class="post-title">Sushi de qualidade fora do centro de Lisboa</p>
</a>
</li>
<li class="col-xs-3 no-padding">
<a href="#">
<img src="img/post-2.png">
<p class="post-title">Sushi de qualidade fora do centro de Lisboa</p>
</a>
</li>
etc


CSS:

#other-posts-container li {
padding: 0 5px;
}

#other-posts-container li img {
max-width: 100%;
height: auto;
}

#other-posts-container li:nth-of-type(1) {
padding-left: 0;
}
#other-posts-container li:nth-of-type(4) {
padding-right: 0;
}

Answer
  1. Your HTML structure is not correct (you don't you rows properly, div is not allowed as a direct child of ul and you use col-xs-12 inside col-xs-12). My HTML solution:

<div class="container-fluid">
  <div class="row">
    <div class="col-xs-3">
      <a href="">
        <img src="http://placehold.it/800x600" class="img-responsive">
        <p>Sushi de qualidade fora do centro de Lisboa</p>
      </a>
    </div>
    <div class="col-xs-3">
      <a href="">
        <img src="http://placehold.it/800x600" class="img-responsive">
        <p>Sushi de qualidade fora do centro de Lisboa</p>
      </a>
    </div>
    <div class="col-xs-3">
      <a href="">
        <img src="http://placehold.it/800x600" class="img-responsive">
        <p>Sushi de qualidade fora do centro de Lisboa</p>
      </a>
    </div>
    <div class="col-xs-3">
      <a href="">
        <img src="http://placehold.it/800x600" class="img-responsive">
        <p>Sushi de qualidade fora do centro de Lisboa</p>
      </a>
    </div>
  </div>
</div>
  1. You can set padding for all your items and add negative margin to row (to properly align whole container).

.row {
  margin-left: -5px;
  margin-right: -5px;
}
.row > [class*='col-'] {
  padding-left: 5px;
  padding-right: 5px;
}

CODEPEN