我有一个这样的父元素和一个子元素
<parent element>
<...>
<...>
<child element></child element>
</...>
<...>
</parent element>
我想让子元素接收父元素/2的宽度。
我是 wondergint,CSS3 是否允许使用类似的东西:
child{
width:parent().parent().parent().width/2 + "px"
}
我不能使用 jquery,也不能向 HTML 添加任何附加代码,我只能访问 CSS 文件。这可能吗?
最佳答案
不完全是,但你可以实现类似的混合 CSS variables和计算
:
这是一个使用父作用域变量的例子
your_parent_element_selector{
--ParentWidth: 100vw;
width: var(--ParentWidth);
}
your_parent_element_selector /* ... */ your_child_selector{
width: calc(var(--ParentWidth) / 2);
/*no need for units for those simple calculations*/
/*this variable is accessible because the child is within
the parent's scope*/
}
这是一个使用“全局”范围变量的例子
:root{
/*[...]*/
--ThisSpecificParentWidth: 100vw;
}
your_parent_element_selector{
width: var(--ThisSpecificParentWidth);
/*accessible bc everything is within :root's scope*/
}
your_parent_element_selector /* ... */ your_child_selector{
width: calc(var(--ThisSpecificParentWidth) / 2);
}
calc
的真正有趣之处在于您可以实现非常复杂的计算,例如:calc((100vw - 2em)/2 + 10vh)
。
作为CSS variables只是自定义属性,您可以像这样完全存储计算结果(注意范围):--prop: calc((100vw - 2em)/2 + 10vh - (var(--margin) * 2)) ;
关于jquery - css3是否允许数学计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45774377/