Kris Hunt
Kris Hunt

Reputation: 2242

Make flexbox items the same height

I'm learning how to use Flexbox, and I can't get my boxes to do what I want. I want:

The main problem I'm facing is that the boxes are not the same size when one has more text than the rest. This is happening despite the parent element having the align-items: stretch attribute, which I thought was supposed to correct that.

Thanks for any help. Here is my code:

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {
        margin: 0;
        padding: 0;
        font-size: 30px;
    }
    
    .parent {
        margin: 0;
        padding: 0;
        display: flex;
        justify-content: space-between;
        align-items: stretch;
        gap: 5px;
    }
    
    .parent li {
        list-style: none;
        background: silver;
        padding: 100px 10px;
        text-align: center;
        flex: 1 0 25%;
        margin: auto;
        box-sizing: border-box;
    }
    
    .parent li a {
        margin: auto;
        padding: 100px 10px;
        text-decoration: none;
        color: #000000;
    }
  </style>
</head>

<body>
  <ul class="parent">
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">This is box number three, and it has a lot more content than the others.</a></li>
    <li><a href="#">Four</a></li>
  </ul>
</body>
</html>

Upvotes: 2

Views: 2331

Answers (1)

manjiro sano
manjiro sano

Reputation: 842

I added random text there, to make sure it would increase the height, and still center to the text.

So basically, what I did, was use what you did and another flexbox on the a tag, to make it center no matter the height.

body {
        margin: 0;
        padding: 0;
        font-size: 30px;
    }
    
    .parent {
        margin: 0;
        padding: 0;
        gap: 5px;
        display: flex;
        align-items: stretch;
        flex-wrap: wrap;
    }
    
    .parent li {
        list-style: none;
        background: silver;
        padding: 100px 10px;
        text-align: center;
        flex: 1;
        margin: auto;
        box-sizing: border-box;
        padding: 5px;
        margin: 5px;
    }
    
    .parent li a {
        margin: auto;
        text-decoration: none;
        color: #000000;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
    }
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <ul class="parent">
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">This is box number three, and it has a sjdsddsd lot more content thddd dsdssdd dssd sdsdsddddddan the others.</a></li>
    <li><a href="#">Four</a></li>
  </ul>
</body>
</html>

Upvotes: 2

Related Questions