基于div而不是屏幕的条件CSS [英] conditional CSS based upon div not screen

查看:99
本文介绍了基于div而不是屏幕的条件CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经做过一些研究并且很接近答案,但是我真的希望仅凭CSS不可能做到。

So I have done some research and am close to an answer, but what I am trying to do may not be possible with CSS alone which I really hope it is.

最终目标是,如果具有id为primary的元素的宽度为915或更小,则将具有一类砖的元素的宽度设置为90%。

The end goal is to set the width of the elements with a class of bricks to 90% if the width of the element with the id of primary is 915 or less.

html片段:

<div id='primary'>
    <div class='bricks'>
        <p>div-1</p>
    </div>
    <div class='bricks'>
        <p>div-2</p>
    </div>
</div>

css片段:

#primary{
    width:100%;
}

.bricks{
    width:45%;
}

@media only screen and ( max-width: 915px ){
    .bricks{
        width:90%;
    }
}

这当前有效,并设置元素的宽度为如果屏幕尺寸小于915像素,则将砖块分类为90%。但是要注意的是,有动态内容可能会或可能不会浮动到具有主ID的元素的左侧和右侧。

This currently works and sets the width of the elements with bricks as a class to 90% if the screen size is less than 915px. However the catch is that there is dynamic content that may or may not be floated to the left and right of the element with the id of primary. This means that the screen size does not always determine the width of the element.

问题:有没有办法为 .bricks设置条件CSS? 仅根据 #primary 的宽度而不是屏幕的大小使用CSS(而不是javascript / php / etc。)?

Question: Is there a way to set conditional CSS for .bricks using only CSS (no javascript/php/etc.) based upon the width of #primary not the size of the screen?

我知道这可以很容易地用javascript完成,但是要使其与其他javascript / jQuery插件一起使用,必须在CSS样式表中而不是在元素样式属性中设置css

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.

推荐答案

无法将if条件放在div宽度上

我知道这可以很容易地用javascript完成,但要与其他javascript / jQuery插件一起使用,必须在CSS样式表中而不是在元素样式属性中设置css。

为此可以在样式表中使用2个不同的类,即

For this you can use 2 different classes in your stylesheet i.e.

.wide {width:90%;}
.half {width:45%;}

现在您可以使用jQuery检查 #primary 容器宽度并设置类:

Now you can check with jQuery the #primary container width and set the class:

const $primary = $("#primary");
$primary
    .find(".bricks")
        .addClass($primary.width() < 915 ? "wide" : "half")

这篇关于基于div而不是屏幕的条件CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆