html - 如何遮蔽奇怪但只有可见的标题?
问题描述
.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
但只有可见的标题?
解决方案
纯 CSS 解决方案
两个纯 CSS 解决方案
解决方案 1
- 使父节点(
<body>
在这种情况下)成为弹性列容器 - 更改
.title:nth-child(odd)
为(even)
- 分配
order: 3
给相邻的兄弟姐妹.test + div
解释
因为.test
仍然在 HTML 中,所以它总是被认为是在奇怪的位置,因此改变阴影模式来纠正这种情况。使用order
flexbox 属性可以让我们直观地移动标签,但就 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
显示该位置的标题,而不是实际存在的标题。所以1
和2
是准确的,但在第三个位置是现在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>
推荐阅读
- xml - 根据另一个变量的值在 XSLT 中创建变量
- node.js - auth0 让客户使用访问令牌连接到我的应用程序
- css - 是否可以将 CSS 代码转换为飞镖代码
- python - 导出 Max/Msp/Jitter 控制台数据
- azure - 每日独立用户累计总数
- javascript - 全局变量是否可以访问箭头函数?
- java - 如何从 Mono 中提取值
类型字段? - pandas - 与 numpy 数组对象和数据框的矩阵乘法
- javascript - 我的 jQuery 不工作,导入 CDN,页面准备好后运行?
- azure-ad-b2c - 如何根据自定义用户属性过滤 azure b2c 中的用户?