CSS selector based on width?

前端 未结 4 727
灰色年华
灰色年华 2020-12-04 02:00

Is there a CSS rule that would match elements based on their width? If not, would it be interesting to propose that in the standard?

One could do something like

相关标签:
4条回答
  • 2020-12-04 02:17

    I just saw an example of media queries within a selector, effectively the same thing, although a pseudo-selector would be very nice and likely supplant media queries. I think it would be nice to have a new pseudo-selector :aspect-ratio(4:3) supporting ranges like :aspect-ratio(>4:3). This would be super convenient for styling responsive elements based on their orientation and width to height ratio.

    0 讨论(0)
  • 2020-12-04 02:26

    Is there a CSS rule that would match elements based on their width?

    No.

    If not, would it be interesting to propose that in the standard?

    Maybe, but not the Selectors standard, because Selectors is not intended to be tightly coupled with the styling aspect of CSS.

    There were proposals to standardize something called "element queries" a few years ago, but other than a few proofs-of-concept, they seem to have mostly dissipated. Probably because they're just not feasible to spec and implement in a way that is robust (cyclic dependencies immediately come to mind).

    0 讨论(0)
  • 2020-12-04 02:26

    It is not possible to do it using CSS3, but you can use Element Queries. Check this library: https://elementqueries.com

    Here is an example:

    @element code and (max-width: 200px) {
      :self {
        white-space: nowrap;
      }
    }
    
    0 讨论(0)
  • 2020-12-04 02:34

    That might become inconsistent because new elements could be unexpectedly affected. I would just add a class that defines {wrap: nowrap;} to any elements in your html. Or if the element width changes on resize, just use some js.

    window.onscroll = function(){
        var elementWidth = document.getElementById('elementID').style.width;
        if(elementWidth < 200){ .. do something .. }
        else{ .. reverse changes .. }
    }
    
    0 讨论(0)
提交回复
热议问题