仅在CSS中维护div的宽高比

时间:2014-06-09 03:00:49

标签: css aspect-ratio

如果我有一个元素(例如div#frame)我想尽可能多地填充屏幕,同时仍保持指定的宽高比(例如16:9),我必须应用哪些样式?我确信Javascript中有一些不同的解决方案,但我想尝试一种只有CSS的方法。

我一直在搜索,虽然已经有some solutions in CSS,但它们使用百分比填充,这是通过宽度值计算的,这意味着纵横比仅在浏览器水平调整大小时保持,而不是垂直调整大小。

#frame
{
    /* centered */
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    margin: auto;
    position: fixed; 

    /* aspect ratio */
    width: 100%;
    height: 0px;
    padding-bottom: 56.25%;
}

这很好用,但我想要一个解决方案,在水平和垂直方向调整大小时仍会保持元素的宽高比,如下面嵌入的图像所示。

enter image description here

1 个答案:

答案 0 :(得分:1)

我不认为可以使用css属性来设置基于高度的元素的宽度,因为它们是要使用的。所以你最好开始考虑那里的JS;) 虽然有一个黑客涉及图像,但它并不好。也许你可以扩展这个想法(我还是更喜欢JS)。

您需要的图像具有您希望框架的最大尺寸。透明的gif应该这样做。然后让您使用包装器上的inline-block让图像的本机行为设置包装器的大小。然后在包装器中使用绝对定位的元素来保存您的内容:

<div class="wrapper">
    <img src="https://cdn.boldernet.net/0/0/856/856567-450.jpg">
    <div class="content">
        content
    </div>  
</div>

CSS:

body {
    text-align: center;
}

.wrapper > img {
    display:block;
    max-width: 100%;
    max-height: 100%;
}
.wrapper {
    display: inline-block;
    position: relative;
    top: 50%;
}
.content {
    position: absolute;
    background: blue;
    left: 0;
    top: -50%;
    width:100%;
    height:100%;
}