-2

enter image description here

How to create a responsive square container in which to place elements?

oei
  • 571
  • 1
  • 5
  • 16

2 Answers2

1

You use viewport units

div {
  width: 40vw;
  height: 40vw;
  background: black url(http://www.lorempixel.com/500/500/nature) center no-repeat;
  background-size: contain;
}
<div>
</div>

Or percent

html, body {
  height: 100%;
}
div {
  width: 40%;
  height: 40%;
  background: black url(http://www.lorempixel.com/500/500/nature) center no-repeat;
  background-size: contain;
}
<div>
</div>

And here is a post showing an aspect ratio solution: Maintain the aspect ratio of a div with CSS

Community
  • 1
  • 1
Asons
  • 84,923
  • 12
  • 110
  • 165
0

You currently can't assign the same width to a html element as the height if you use %-s. You need to use javascript

var element = document.getElementById("your-element");
element.style.height = element.style.width;
//Note: you need to put after the style tags or you need to make it load after fhe document has been loaded
Bálint
  • 4,009
  • 2
  • 16
  • 27