Search code examples
csscustom-data-attribute

CSS attribute select when any string


I have a data attribute data-modals. I would like to target this with CSS when the property has a value. I don't mind what the value is.

I can find guides for selecting when the attribute exists, or specific values, but not for 'any' value - the equivalent of '*'.

ie.

<element data-modals="" /> should not be targeted

<element data-modals="any text" /> should be targeted


Solution

  • You can the CSS Attribute Selector like this:

    element[data-modals]:not([data-modals=""]) {
      color: red;
    }
    

    Example:

    p[data-modals]:not([data-modals=""]) {
      color: red;
    }
    <p data-modals="">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Corrupti, fugit.
    </p>
    
    <p data-modals="any text">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Corrupti, fugit.
    </p>
    
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Corrupti, fugit.
    </p>




    Some useful links: