首页 > 解决方案 > 如何遮蔽奇怪但只有可见的标题?

问题描述

.test{
display:none;
}

.title:nth-child(odd){
  background: #ddd;
}
<div class='title'>lorem</div>
<div class='title'>lorem</div>
<div class='title test'>lorem</div>
<div class='title'>lorem</div>
<div class='title'>lorem</div>
<div class='title'>lorem</div>
<div class='title'>lorem</div>

如果test是可见的 - 没有问题 -odd标题是阴影的。

如果test不可见 - 阴影规则丢失。

如何遮蔽odd但只有可见的标题?

标签: htmlcss

解决方案


纯 CSS 解决方案

两个纯 CSS 解决方案

解决方案 1

  • 使父节点(<body>在这种情况下)成为弹性列容器
  • 更改.title:nth-child(odd)(even)
  • 分配order: 3给相邻的兄弟姐妹.test + div

解释

因为.test仍然在 HTML 中,所以它总是被认为是在奇怪的位置,因此改变阴影模式来纠正这种情况。使用orderflexbox 属性可以让我们直观地移动标签,就 HTML 代码本身而言,位置仍然相同。将第 4 个 div 放入第 3 个明显不会将其更改为奇数,它将保留偶数标签的阴影。


解决方案 2

  • 让所有<div> color:transparent
  • 为每次潜水分配一个::before伪类content:n n=original position number/for 3+ offset by +1
  • 全部div::before color:#000

    解释

此解决方案用于::Before显示该位置的标题,而不是实际存在的标题。所以12是准确的,但在第三个位置是现在4等等。最后一个 titledisplay:none代替了 position 3 .test。这个复杂的解决方案是在 JosephSible 让我注意到标题不按顺序出现所以解决方案 1 “不起作用”时出现的,而我请求不同,因为 OP 从未提及顺序,解决方案 2没有损坏。请查看Demo2。


演示 1

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      display: flex;
      flex-flow: column nowrap;
    }
    
    .title:nth-child(even) {
      background: #ddd;
    }
    
    .test {
      display: none;
    }
    
    .test+div {
      order: 3
    }
  </style>
</head>

<body>
  <div class='title'>lorem</div>
  <div class='title'>lorem</div>
  <div class='title test'>lorem</div>
  <div class='title'>lorem</div>
  <div class='title'>lorem</div>
  <div class='title'>lorem</div>
  <div class='title'>lorem</div>
</body>

</html>


演示 2

<!DOCTYPE html>
<html>

<head>
  <style>
    .title:nth-child(even) {
      background: #ddd;
    }
    
    div {
      color: transparent;
    }
    
    .test {
      background: #ddd;
    }
    
    div:first-of-type::before {
      content: '1';
    }
    
    div:nth-of-type(2)::before {
      content: '2';
    }
    
    .test::before {
      content: '4'
    }
    
    .test+div::before {
      content: '5'
    }
    
    .test+div+div::before {
      content: '6'
    }
    
    .test+div+div+div::before {
      content: '7';
    }
    
    .test+div+div+div+div {
      display: none;
    }
    
    div::before {
      color: #000
    }
  </style>
</head>

<body>
  <div class='title'>1</div>
  <div class='title'>2</div>
  <div class='title test'>3</div>
  <div class='title'>4</div>
  <div class='title'>5</div>
  <div class='title'>6</div>
  <div class='title'>7</div>
</body>

</html>


推荐阅读