CSS:保持div相对于其宽度的高度 [英] CSS: Keeping a div's height relative to its width

查看:124
本文介绍了CSS:保持div相对于其宽度的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与此问题非常相似: CSS: 100%宽度或高度,同时保持宽高比?

My question is very similar to this question: CSS: 100% width or height while keeping aspect ratio?

我有一个位置固定的div。 div的 width 必须是100%,其高度正好是其宽度的1/6。是否有<-webkit-calc()这样做?

I have a div whose position is fixed. The width of the div must be 100% and its height exactly 1/6th of its width. Is there a -webkit-calc() way of doing this?

注意:因为缩放/方向改变会影响宽度/高度。

Note: JS solutions are not preferred as a zoom/orientation change can affect the width/height.

推荐答案

我不是使用 -webkit-calc()。我已将 1px 插入外部 div 6px c>已将 position:fixed 应用于它,并将图像设置为 width 100% position:relative 。然后我添加了一个内部 div ,它绝对定位为与它的祖先一样高和宽。

Is this what you are after? I'm not using -webkit-calc() at all. I've inserted a 1px by 6px image into a outer div which has position: fixed applied to it, and set the image to have a width of 100% and position: relative. Then I have added an inner div which is absolutely positioned to be as high and wide as its ancestor.

现在您可以更改外部 div 的宽度,以及图像的 width :100%设置将确保外部和内部 div 的保证总是具有等于它们的1/6的高度宽度(或者至少尽可能接近等于它可以得到的,高度将被四舍五入为最接近的整像素数)。任何内容都可以进入内部 div

Now you can change the width of the outer div, and the images' width: 100% setting will ensure that both the outer and the inner div's are guaranteed to always have a height equal to 1/6th of their width (or at least as close to exactly equal as it can get, the heights will be rounded off to the closest whole number of pixels). Any content could go inside the inner div.

HTML

<div>
  <div></div>
  <img src="https://dl.dropboxusercontent.com/u/6928212/sixbyone.png" />
</div>

CSS

html, body {
  margin: 0px;
  padding: 0px;
}
div {
  position: fixed;
  width: 100%;
}
div > div {
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;      
}
img {
  width: 100%;
  display: block;      
  position: relative;
}

这里是 jsFiddle 显示所请求的行为。

Here's a jsFiddle showing the requested behaviour.

这篇关于CSS:保持div相对于其宽度的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆