6

所以我已经做了一些研究并且接近答案,但是我想要做的事情可能仅靠 CSS 是不可能的,我真的希望是这样。

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

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 的元素的左侧和右侧。这意味着屏幕大小并不总是决定元素的宽度。

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

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

4

1 回答 1

5

没有办法在 div width 上设置 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%;}

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

const $primary = $("#primary");
$primary
    .find(".bricks")
        .addClass($primary.width() < 915 ? "wide" : "half")
于 2013-06-19T05:37:56.707 回答