skip to Main Content

Base scenario:

<div class="flex">
  <div id="avatar" />
  <div id="info"/>
</div>

Assuming info will have a dynamic height, based on its content, how can we make avatar be always square?

example 1

In the first example, info has 160px height, so avatar is a 160×160 square.
In the second example, info has more content and its height is 305px, same applies to the avatar

Is there a css-only solution?

I was playing with Tailwind: https://play.tailwindcss.com/5ooxVe8F7E, but the green div in this link should have the same height as the red one.

2

Answers


  1. in display:flex with flex-direction:row the height of your flex items are calculated based on the largest flex-item, so when you apply height:305px to info , comparing info with avatar which has 160px height, info now is taller and larger than the avatar, so it applies 305px height to avatar because it is the largest flex-item.

    one solution to retrieve avatar content height is to set its height based on %, like height:60% or height:100% (the number doesn’t matter and the unit is important) then avatar will retrieve its content and original height.

    Login or Signup to reply.
  2. There are various ways to do this. Here’s one:

    article {
      display: grid;
      grid-template-columns: auto 1fr;
      grid-template-rows: 1fr;
      padding: 40px;
    }
    
    .avatar {
      grid-area: 1/1/2/2;
      aspect-ratio: 1;
      position: relative;
    }
    
    .info {
      grid-area: 1/2/2/3;
      background: rgb(170, 108, 108);
    }
    
    img {
      position: absolute;
      width: 100%;
    }
    
    body {
      background: #30353b;
    }
    <article>
      <div class="avatar">
        <img src="https://picsum.photos/id/1012/600/600">
      </div>
      <div class="info">
        info<br />
        info<br />
        info<br />
        info<br />
        info<br />
        info
      </div>
    </article>

    I’ll let you sort out how do integrate this into your framework. (IMHO, frameworks are more trouble than they’re worth.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search