conditional CSS based upon div not screen

眉间皱痕 提交于 2019-12-22 18:46:48

问题


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.

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 snippet:

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

css snippet:

#primary{
    width:100%;
}

.bricks{
    width:45%;
}

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

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.

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?

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.


回答1:


There is no way to put a if condition on a div width.

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.

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

.width90 {width:90%;}
.width45 { width:45%;}

Now you can check by jQuery the main width div (#primary )

 var primaryDiv = $("#primary");
 var primaryWidth = primaryDiv .width();

and check for condition

 if(primaryWidth < 915){
    primaryDiv.find(".bricks").addClass("width90");
}else{
    primaryDiv.find(".bricks").addClass("width45");
}


来源:https://stackoverflow.com/questions/17183302/conditional-css-based-upon-div-not-screen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!