较少的属性“选择器开始”带有不同的后缀

发布于 2025-01-23 21:19:06 字数 470 浏览 4 评论 0原文

我有一个针对两个HTML元素的属性选择器:

div {
  width: 40px;
  aspect-ratio: 1;
  margin: 5px;
  background-color: lavender;
}

div[class^="tag-"] {
  outline: 2px solid tomato;
}
<div class="tag-start"></div>
<div class="tag-end"></div>

我可以创建一个较小的选择器,该选择器既可以使用属性选择器作为起点?

I have an attribute selector that targets two HTML elements:

div {
  width: 40px;
  aspect-ratio: 1;
  margin: 5px;
  background-color: lavender;
}

div[class^="tag-"] {
  outline: 2px solid tomato;
}
<div class="tag-start"></div>
<div class="tag-end"></div>

Can I create a Less selector that targets both using the attribute selector as a starting point?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贱贱哒 2025-01-30 21:19:06

根据 css 4级规范,您当前的选择器可能不是最佳解决方案。

在下图中,您的选择器将仅匹配示例一个和第二个,因为 a>您正在使用的只有属性值的开头,而不是每个空间分离的classList中的值:

div {
  width: 40px;
  aspect-ratio: 1;
  margin: 5px;
  background-color: lavender;
}

div[class^="tag-"] {
  outline: 2px solid tomato;
}
<div class="tag-start">1</div>
<div class="tag-end">2</div>
<div class="will-not-work tag-test">3</div>

由于所有较少的代码转录到CSS,较少的代码将无法匹配CSS本身所无法匹配的任何内容,但包括所有可能遵循tag的可能排列 - ...

我建议您使用<<< a href =“ https://developer.mozilla.org/en-us/docs/lealen/lealen/html/howto/use_data_attributes” rel =“ nofollow noreferrer”> data属性在这里而不是类。

div {
  width: 40px;
  aspect-ratio: 1;
  margin: 5px;
  background-color: lavender;
}

div[data-tag] {
  outline: 2px solid tomato;
}

div[data-tag="start"] {
  outline: 4px solid hotpink;
}
<div data-tag="start">1</div>
<div data-tag="end">2</div>
<div data-tag="test" class="will-work">3</div>

Your current selector may not be the best solution as per the CSS Level 4 Specification.

In the below snippet your selector will match only examples one and two because the attribute-substrings selector you're using will only match the beginning of an attribute value, not each space separated value in a classlist:

div {
  width: 40px;
  aspect-ratio: 1;
  margin: 5px;
  background-color: lavender;
}

div[class^="tag-"] {
  outline: 2px solid tomato;
}
<div class="tag-start">1</div>
<div class="tag-end">2</div>
<div class="will-not-work tag-test">3</div>

Since all less code transpiles to CSS, less won't be able to match anything CSS itself can't, short of including all possible permutations that could follow tag-...

I suggest you use a data attribute here rather than a class.

div {
  width: 40px;
  aspect-ratio: 1;
  margin: 5px;
  background-color: lavender;
}

div[data-tag] {
  outline: 2px solid tomato;
}

div[data-tag="start"] {
  outline: 4px solid hotpink;
}
<div data-tag="start">1</div>
<div data-tag="end">2</div>
<div data-tag="test" class="will-work">3</div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文