Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional CSS based upon div not screen

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.

like image 937
amaster Avatar asked Jun 19 '13 05:06

amaster


1 Answers

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.

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

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")
like image 158
GajendraSinghParihar Avatar answered Nov 15 '22 10:11

GajendraSinghParihar