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

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

问题描述

我的问题与这个问题非常相似:CSS:100% 宽度或高度同时保持纵横比?

我有一个位置固定的 div.div 的宽度必须是 100% 并且它的高度正好是它的 宽度的 1/6.有没有 -webkit-calc() 方法来做到这一点?

注意:JS 解决方案不是首选,因为缩放/方向更改会影响宽度/高度.

解决方案

这就是你想要的吗?我根本没有使用 -webkit-calc() .我已经将 1px by 6px 图像插入到外部 div 中,该图像应用了 position: fixed,并将图像设置为具有 100%position:relativewidth.然后我添加了一个内部 div,它的位置绝对与其祖先一样高和宽.

现在你可以改变外层div的宽度,图片的width: 100%设置将确保外层和内层div 的高度保证总是等于其宽度的 1/6(或至少尽可能接近完全相等,高度将四舍五入到最接近的像素整数).任何内容都可以进入内部 div.

HTML

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

CSS

html, body {边距:0px;填充:0px;}div {位置:固定;宽度:100%;}div >div {位置:绝对;顶部:0px;右:0px;底部:0px;左:0px;}图片{宽度:100%;显示:块;位置:相对;}

这是一个显示请求行为的 jsFiddle.

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

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.

解决方案

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.

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;
}

Here's a jsFiddle showing the requested behaviour.

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

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