htmlcssstyles

Change CSS based on an element's width


Is there a pure CSS way of specifying different CSS styles for an element, only active when it's, let's say, under a certain width?

Similar to an @media query, but not the whole screen, just the element. Something like...

.element {
    background: blue;
}
.element[max-width=300] {
    background: red;
}

I know how I'd do it with JavaScript, but that sounds so overly complicated... >.<


Solution

  • Media queries will only work on the size of the screen of the device i.e. on the media that the website is viewed on. So, unfortunately, you can't do this with CSS.

    JavaScript may sound like a complicated and over-the-top method, but it would be the best, most efficient and most maintainable method. If you were to use this with a lot of elements on a page, you could even look at using something like React or Angular. These would be would be very over-the-top for something small but would make it easier to maintain and work with, if you were doing this on a larger scale.

    If you could work out what the size of the entire screen would be for the size of those particular elements at the size you would want to change them, you could try and use a media query. This would probably be more complicated that JavaScript and probably would make maintenance even more complicated.