所以我做了一些研究并且接近答案,但是我想要做的事情可能无法单独使用 CSS,我真的希望它是。
如果 id 为 primary 的元素的宽度为 915 或更小,则最终目标是将具有砖类的元素的宽度设置为 90%。
html片段:
<div id='primary'>
<div class='bricks'>
<p>div-1</p>
</div>
<div class='bricks'>
<p>div-2</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
css 片段:
#primary{
width:100%;
}
.bricks{
width:45%;
}
@media only screen and ( max-width: 915px ){
.bricks{
width:90%;
}
}
Run Code Online (Sandbox Code Playgroud)
如果屏幕尺寸小于 915 像素,这当前有效并将砖作为类的元素的宽度设置为 90%。然而,问题是有动态内容可能会或可能不会浮动到 id 为主要元素的元素的左侧和右侧。这意味着屏幕尺寸并不总是决定元素的宽度。
问题:有没有办法.bricks根据宽度而#primary不是屏幕大小来设置仅使用 CSS(没有 javascript/php/etc.)的条件 CSS ?
我知道这可以用 javascript 轻松完成,但要使其与其他 javascript/jQuery 插件一起使用,css 必须在 CSS 样式表中设置,而不是在元素样式属性中。
无法在 div 宽度上放置 if 条件。
I know that this could easily be done with javascript, but for it to work with other javascript/jQuery plugins, the css has to be set in the CSS stylesheet not in the element style attribute.
为此,您可以在样式表中使用 2 个不同的类,即
.wide {width:90%;}
.half {width:45%;}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用 jQuery 检查#primary容器宽度并设置类:
const $primary = $("#primary");
$primary
.find(".bricks")
.addClass($primary.width() < 915 ? "wide" : "half")
Run Code Online (Sandbox Code Playgroud)