如何创建响应式方形容器?

时间:2016-03-17 17:50:14

标签: css css3

enter image description here

如何创建一个放置元素的响应式方形容器?

2 个答案:

答案 0 :(得分:1)

您使用viewport单位

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

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>

这是一篇显示aspect ratio解决方案的帖子:Maintain the aspect ratio of a div with CSS

答案 1 :(得分:0)

如果您使用%-s,则目前无法为html元素指定相同的宽度作为高度。你需要使用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