自定义元素选择器

问题描述 投票:5回答:4

是否可以使用CSS选择所有自定义元素?我想使所有自定义元素默认为块元素(大多数浏览器默认使它们为内联),然后根据需要覆盖此元素。

我的规则可能看起来像这样:

*::custom {
    display: block;
}

所有自定义元素在标准中都有破折号,因此我可以利用它来创建一条规则,但是在许多/最新的浏览器中,它会比较慢,因为它需要使用正则表达式。如果有内置的选择器,则可能会更快。

html css css-selectors custom-element
4个回答
2
投票

不,没有伪选择器可以做到这一点。

但是,一种肯定不是最佳解决方案的方法是使用这种类型的CSS:

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

这会工作!另一方面,如果添加了新元素,则需要将该元素添加到非选择器中。是的。

^。^


1
投票

向您的自定义元素添加惰性自定义属性:

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

0
投票

您可以像下面这样简单地使用css:

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

我已经在Firefox和Chrome中对此进行了测试。虽然不确定实际的兼容性。请在您的环境中进行测试。


0
投票

以下是基于Florrie的答案的解决方法::not(html):not(head):not(title):not(base):not(link):not(meta):not(style):not(body):not(article):not(section):not(nav):not(aside):not(h1):not(h2):not(h3):not(h4):not(h5):not(h6):not(hgroup):not(header):not(footer):not(address):not(p):not(hr):not(pre):not(blockquote):not(ol):not(ul):not(li):not(dl):not(dt):not(dd):not(figure):not(figcaption):not(div):not(main):not(a):not(em):not(strong):not(small):not(s):not(cite):not(q):not(dfn):not(abbr):not(data):not(time):not(code):not(var):not(samp):not(kbd):not(sub):not(sup):not(i):not(b):not(u):not(mark):not(ruby):not(rb):not(rt):not(rtc):not(rp):not(bdi):not(bdo):not(span):not(br):not(wbr):not(ins):not(del):not(picture):not(img):not(iframe):not(embed):not(object):not(param):not(video):not(audio):not(source):not(track):not(map):not(area):not(math):not(svg):not(table):not(caption):not(colgroup):not(col):not(tbody):not(thead):not(tfoot):not(tr):not(td):not(th):not(form):not(label):not(input):not(button):not(select):not(datalist):not(optgroup):not(option):not(textarea):not(keygen):not(output):not(progress):not(meter):not(fieldset):not(legend):not(script):not(noscript):not(template):not(canvas)

此外,您还必须考虑SVG和MathML名称空间。

  • 一种方法是仅以类似方式添加其标签。
  • 在某些情况下(广告屏蔽),为选择器添加几个可能的父母可能足以避免子女。类似于:-webkit-any(body, div) > :not(...。参见:is(), :matches(), :any()
  • 一旦实现,选择器级别4应该允许类似:not(math *, svg *)的内容。
  • @namespace可以使用,类似于@namespace xhtml "http://www.w3.org/1999/xhtml"; xhtml|*:not(...
© www.soinside.com 2019 - 2024. All rights reserved.