Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a div's width be the same as it's height when it's in a flexbox

Tags:

html

css

flexbox

I have a headerbar with the usual content. App-Logo, nav, some controls.

The navbar's height is not set, but determined by its contents. It is a flex container.

Now I want the App-Logo to stretch to the vertical available space and maintain its aspect ratio.

Here is what it should look like:

Navbar Goal

Here is the code which achieves the image above:

.headerbar {
  display: flex;
  align-items: stretch;
  gap: 1rem;
  padding: .5rem;
  background: #f0f0f0;
  border-bottom: 1px solid gray;
}

.logo {
  aspect-ratio: 1 / 1; /* Not working */

  border-radius: 5px;
  background: radial-gradient(circle, rgba(63, 94, 251, 1) 0%, rgba(252, 70, 107, 1) 100%);
}
<div class="headerbar">
  <div class="logo"></div>
  <p>Link 1</p>
  <p>Link 2</p>
  <p>Link 3</p>
</div>

Link to code: https://jsfiddle.net/v2ta54eg/19/

As you can see, the logo is not visible. It seems to only stretch itself, as expected, but the aspect-ratio property has no effect on the width. The width stays 0.

What tried to do, was use aspect-ratio: 1 / 1 and I expected it to set the width to the same amount as the height. This is because the height is kind of set with aling-self: stretch.

So the question is:

How can I make a div have the same width as height, taking the height from the flex parent align-items: stretch / align-self: stretch?

like image 491
Chiff Shinz Avatar asked Oct 31 '25 18:10

Chiff Shinz


1 Answers

You can definitely do this with a little extra HTML:

article {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
}

.headerbar {
  display: flex;
  padding: .5rem;
  background: #f0f0f0;
  border-bottom: 1px solid gray;
}

.logo {
  aspect-ratio: 1;
  height: 100%;
  border-radius: 5px;
  background: radial-gradient(circle, rgba(63, 94, 251, 1) 0%, rgba(252, 70, 107, 1) 100%);
}

.links {
  display: flex;
  gap: 1em;
  padding: 10px;
  flex: 1 0 0;
}
<article>
  <div class="headerbar">
    <div class="logo">
    </div>
    <div class="links">
      <p>Link 1</p>
      <p>Link 2</p>
      <p>Link 3</p>
    </div>
  </div>
</article>
like image 151
ralph.m Avatar answered Nov 03 '25 08:11

ralph.m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!