定位h2 ::之后,包含h2 ::之前

问题描述 投票:2回答:2

如何将特定的css专门应用于h2 :: after,然后还要有h2 :: before?

.region-sidebar-second .block > h2::after, .region-content .block > h2:after {
  content: "";
  display: block;
  width: 30px;
  margin-bottom: 1.25rem;
  margin-top: 0.75rem;
  border: 0.5px solid #252525;
  position: relative;
}

#block-block-51 h2::before{
  padding-right: 5px;
  content: "\f02d";
  font-family: "Font Awesome 5 Pro",sans-serif;
  font-weight: 900;
}

::after_selector_for_those_h2_that_have_a_::before{
   left:2rem;
}
css pseudo-element
2个回答
2
投票

您至少还不能。这将需要一个选择器来选择具有before伪元素(不存在)的元素。选择器仅适用于DOM中可用的内容。

有一个工作草案可以通过pseudo-class selector :has()启用此功能。它看起来如下:

:has()

但是,来自文档:

在当前规范中:没有被标记为实时选择器配置文件的一部分,这意味着它不能在样式表中使用;仅具有element:has(::before)::after 之类的功能。


1
投票

您可以考虑使用CSS变量对此进行模拟。让我们考虑将要应用document.querySelector()的h2由before选择。然后,您可以执行以下操作:

#block-block-51 h2
:root {
  --c:none; /* Default value (don't show the pseudo element)*/
}


#block-block-51 h2::before{
  content: "I have a before"
}

#block-block-51 h2 {
  --c:initial; /* Reset the value to use the fallback (show the pseudo element)*/
}


h2::after {
  content:var(--c,"");
  display:inline-block;
  height:20px;
  width:20px;
  background:red;
}

技巧是使用CSS变量定义<div id="block-block-51"><h2> Me!</h2></div> <h2>not Me ...</h2>,在该变量中将content设置为值(因此未定义),然后使用所需的选择器重置该值,我们将考虑后备none和伪元素将被定义。

有关更多详细信息的问题:""


以您的示例为例:

How to store inherit value inside a CSS custom property (aka CSS variables)?
© www.soinside.com 2019 - 2024. All rights reserved.