conditional CSS based upon div not screen

12,427

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")
Share:
12,427
amaster
Author by

amaster

I am a self-taught web developer and programmer. I started my first web development project in 2007 and have completed many successful projects since. I enjoy coding and learning technology and tricks with old technology.

Updated on June 24, 2022

Comments

  • amaster
    amaster almost 2 years

    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.