141

Is there a CSS selector that applies to non-empty attributes? Using :not([Data-Attribute='']) matches if the attribute is non-existing, too.

I'm looking for something like [Data-Attribute!=''].

2
  • It wouldn't be similar to [Data-Attribute!=''] if you're talking about the jQuery selector, because the jQuery selector is equivalent to :not([Data-Attribute='']) and does match if the attribute is not specified. Commented Jun 22, 2013 at 9:00
  • 3
    Possible duplicate of Select elements where attribute is non-empty Commented May 19, 2016 at 20:41

3 Answers 3

297

try this

<style>
    [Data-Attribute]:not([Data-Attribute=""])
    {
        background-color: Red;
    }
</style>
Sign up to request clarification or add additional context in comments.

4 Comments

I've seen a better (or different) solution here: stackoverflow.com/questions/16429220/…
@Sven The only solution on that link that answers this question (select a specific data attribute that is not empty) is identical to this answer.
Yup, the solution provided here targets what he needs, the one in the link above requires counter-styling.
This solution affects unexpected elements (if matching attr title).
-1

If you prefer a sass/scss solution:

.selector {
  @include attr-isset('attribute-name') {
    ...styles
  }
}

you may use this mixin:

/**
 * Requires
 */
@use "sass:meta";

/**
 * Select current scope only if a given attribute is set
 * @param {string} $attribute - Attribute name, default: 'class'
 * @param {boolean} $empty - Allow empty attribute
 * @param {string} $error - Error message prefix
 * @output Wraps given content styles to apply only if the current scope element has the given attribute
 */
@mixin attr-isset($attribute: 'class', $empty: false, $error: 'attr-isset::') {
  @if meta.content-exists() != true {
    @error '#{$error}@content is required';
  }
  @if $empty {
    &[#{$attribute}] {
      @content;
    }
  } @else {
    &[#{$attribute}]:not([#{$attribute}='']) {
      @content;
    }
  }
}

Comments

-3

for style false support

[{ font: ["sofia", "slabo", "roboto", "inconsolata", "ubuntu", false] }]

.ql-snow .ql-picker.ql-font .ql-picker-item:not([data-value])::before {
content: "default";
font-family: none !important;}

.ql-snow .ql-picker.ql-font .ql-picker-label:not([data-value])::before {
content: "default";}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.