Div Square, width size based on 100% height

Viewed 19360

I'm trying to make a responsive square with the width size based on the (100%) height of the element. I believe it's impossible using only CSS.

The square width should be equal to the height (100% of the large container. The large container is more than 100% of the screen). The ratio has to be width=height to keep the square.

9 Answers

You could do this with a tiny inline image. No JS, no extra files.

.container {
  height: 150px;
  width: 100%;
  text-align: center;
  background: #acd;
}
     
.square {
  display: inline-block;
  height: 100%;
  background: #691;
}
<div class="container">
  <div class="square">
    <img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" height="100%">
  </div>
</div>

Take a look... at the aspect-ratio property.

This property makes creating a square div based on height, in the easiest method possible. Here's some example code:

h2 {
  font-family: calibri;
}

#parent {
  height: 96px;
  width: 256px;
  background: grey;
  margin-bottom: 16px;
}

#child {
  height: 80px;
  aspect-ratio: 1 / 1;
  background: lightgrey;
}

#anotherParent {
  height: 96px;
  width: 256px;
  background: grey;
}

#anotherChild {
  height: 50%;
  aspect-ratio: 1 / 1;
  background: lightgrey;
}
<h2>Absolute height (80px/96px)</h2>
<div id="parent">
  <div id="child">
  </div>
</div>

<h2>Relative height (50%)</h2>
<div id="anotherParent">
  <div id="anotherChild">
  </div>
</div>

Here are a couple of links to help you understand the aspect-ratio property:

You can assign width and height to the container like this

.container{
      width: '100vh',
      height: '100vh',
}

It will create a square div with 100% height and width=height.

Related