CSS的唯一方式设置一个div到90%的宽度和3:1的宽高比 [英] CSS-only way to set a div to 90% width and 3:1 aspect ratio
问题描述
我有一个div,我想设置为其父容器的宽度的90%,
,我想要设置它的高度以达到特定的宽高比,比如3:1。
I have a div that I want to set to 90% of its parent container's width, and I want its height to be set so as to achieve a specific aspect ratio, say 3:1.
.mydiv {
width: 90%
height: 30%(of-width);
}
有没有办法做到这一点, >
Is there any way to do this that does not involve JavaScript?
推荐答案
如果你的容器div有固定宽度,那么你的90%宽度div也有固定宽度。看看这是这个宽度(计算或使用类似firebug的工具),然后计算3:1宽高比,并应用像素的高度。
If your container div has a fixed width, then your 90% width div has as well a fixed width. Look which is this width (calculate or use a tool like firebug) and then calculate the 3:1 aspect ratio and apply a height in pixels.
如果你的容器div固定宽度,那么90%也是可变的。因此,使用动态值管理的唯一方法是使用javascript。
If your container div hasn't a fixed width, then the 90% is as well variable. So the only way you have to manage with dynamic values is to use javascript.
UPDATE
有一个 aspect-ratio
属性,但它不是一个标准的。我没有测试它,但它应该与webkit浏览器工作。以下是关于此媒体资源的链接:
There is a aspect-ratio
property but it's not a standard one. I haven't tested it, but it should work with webkit browsers. Here it's a link talking about this property:
http ://www.xanthir.com/blog/b4810
如果您真的想要执行这个跨浏览器,还有两个选项:
If you really want to do this cross-browser, there are two more options:
您可以使用以下链接中解释的解决方法。它不是很干净,因为它使用的图像,但它的作者说,它适用于Firefox 3.5,Safari 4和Internet Explorer 7& 8.链接:
You can use the workaround explained in following link. It's not very clean because it uses an image, but its author says it works for Firefox 3.5, Safari 4 and Internet Explorer 7 & 8. The link:
http:// lab。 veille.jp/aspectratio/
这种情况下的另一个丑陋(很多代码)将使用 CSS3媒体查询。你应该看看你的div的宽度是不同的窗口宽度,计算宽高比在每种情况下,并应用它的高度。您定义的媒体查询越多,顺利。
Another ugly for this case option (a lot of code) would be using CSS3 media-queries. You should look which is the width of your div for different windows width, calculate the aspect ratio in each case and apply it to the height. The more media-queries you define, smoother it will be.
@media only screen and (max-width:900px){
div {
width: /*Calculate your width*/
height: /*Calculate your aspect ratio*/
}
}
/*50px gap... if you decrease the gap it will be smoother*/
@media only screen and (max-width:850px){
div {
width: /*Calculate your width*/
height: /*Calculate your aspect ratio*/
}
}
/*And more, and more... till you rich maybe a setted min-width*/
这篇关于CSS的唯一方式设置一个div到90%的宽度和3:1的宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!