2017-08-25 88 views
0

我需要将元素的高度设置为其宽度的2/3。我知道我可以用类似于$(this).height($(this).width()/3*2)使用css定义基于宽度的高度

这样的东西使用JS来做到这一点,我可以使用不带预处理器的直接CSS来做同样的事情吗?

+1

您可以将元素设置为'高度:0;填充底:66.67%',但随后你必须绝对位置的任何儿童的内容。这是否实际取决于元素内部的内容。 – Blazemonger

+0

@Blazemonger它实际上按照我需要的方式工作。谢谢 –

+0

添加为答案 – Blazemonger

回答

-1

您可以将元素设置为height: 0;padding-bottom: 66.67%,但您必须绝对定位任何子内容。这是否实际取决于元素内部的内容。

1

没错没有为此

流行的技巧,但现在我们有CSS变量/自定义属性,你可以使用。 不完全支持虽然

.p{ 
 
    width: 60px; 
 
} 
 

 
.c { 
 
    background-color: cyan; 
 
    width: 100%; 
 
    padding-top: 150%; 
 
} 
 

 
/* advanced css custom properties */ 
 
.a { 
 
    --width: 60px; 
 
    width: var(--width); 
 
    height: calc(var(--width)*1.5); 
 
    background-color: rebeccapurple; 
 
}

 
<!-- hack using padding --> 
 
<div class="p"> 
 
    <div class="c"> 
 
     
 
    </div> 
 
    </div> 
 
    <br> 
 
    
 
    <!-- advanced css using custom properties/ css variables --> 
 
    <div class="a"></div>