Custom Element Selector

2019-06-21 05:28发布

问题:

Is there a way to select all custom elements with CSS? I want to make all custom elements block elements by default (most browsers make them inline by default), and then override this as necessary.

My rule may look something like this:

*::custom {
    display: block;
}

All custom elements have dashes in the standard, so I could create a rule taking advantage of that, but it would be slower on many/most current browsers, as it would need to use regular expressions. If there were a built-in selector, this would probably be faster.

回答1:

No, there isn't a pseudo selector to do that.

One certainly not optimal solution, however, would be to use this type of CSS:

:not(html, head, body, h1, h2, h3, h4, h5, h6, div, ...) {
  /* Code here */
}

It would work! On the down side if ever new elements are added you need to add that element into your not-selector. Yay.

^.^



回答2:

Add an inert custom attribute to your custom elements:

<some-element cutom-elem /> <other-element custom-elem />
<script> 
  var customs = document.querySelectorAll( "*[custom-elem]" )
</script>
<style>
    *[custom-elem] { display: block ; }
</style>


回答3:

You can simply use css like below:

custom-element{
    color: white;
    min-height: 20px;
}

I have tested this in Firefox and Chrome. Not sure about actual compatibility though. Please test on your environments.