【问题标题】:CSS - select all elements that has class starting with prefixCSS - 选择所有类以前缀开头的元素
【发布时间】:2020-12-03 22:34:50
【问题描述】:

需要定位具有以depth-开头的特定类的每个元素

我尝试使用 CSS 进行定位:

[class^="depth-"] {
    margin-left: 40px;
}

但它仅在目标类是类顺序中的第一个时才有效。

就我而言:

<div class="comment byuser comment-author-admin odd alt depth-2 parent" id="comment-13">
    <div id="div-comment-13" class="media">
        ...
    </div>

    <div class="comment byuser comment-author-admin even depth-3" id="comment-14">
        <div id="div-comment-14" class="media">
            ...
        </div>
    </div>
</div>

【问题讨论】:

  • 你不能手动为你想要的元素添加一个自定义的附加类并在 CSS 中应用属性吗?
  • 您唯一的其他真实选择是[class*="depth-"]。这不是精确的,因为“深度”可以出现在任何地方而不是开始类名。
  • 在 -depth 之前留一个空格可能会有所帮助div[class*=' depth-'],div[class^='depth-'] { }

标签: css wordpress


【解决方案1】:

CSS [attribute^="value"] Selector 仅在整个样式属性值以给定值开头时才有效。如果要使用此选择器,则必须将属性开头的 depth-2depth-3 类移动如下 -

<div class="depth-2 comment byuser comment-author-admin odd alt parent" id="comment-13">
    <div id="div-comment-13" class="media">
        TXT HERE
    </div>

    <div class="depth-3 comment byuser comment-author-admin even" id="comment-14">
        <div id="div-comment-14" class="media">
            MORE HERE
        </div>
    </div>
</div>

这样做不是一个好主意。取而代之的是,您可以使用 CSS [attribute*="value"] Selector 在整个属性中搜索给定值。因此,您的 css 代码将如下所示,无需更改 html -

div[class*="depth-"]{
    margin-left: 40px;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-11
    • 2016-06-14
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多