html - 根据特定类的 sibling 调整 div 的大小

标签 html css html-lists

我发现有一种简单的方法可以计算 <li> 的 sibling 数量标记并返回适合多少 <li> 的 CSS 样式 sibling 有:

ul{
	list-style-type: none;
    display: block;
}

#container{
	width: 100%;
	float: left;
	height: 100%;
	margin-left: 0;
	margin-top: 0;
}


li:first-child:nth-last-child(1) {
	height: 100%;
	background-color: red;
	width: 100%;
}

li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
	height: 100%;
	background-color: blue;
	float: left;
	width: 49%;
  margin-left: 1%;
}

li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
	height: 100%;
	float: left;
	background-color: red;
	width: 33.333%;
}


li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
	height: 100%;
	background-color: blue;
	float: left;
	width: 24%;
  margin-left: 1%;
}
<div id="container">
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
</div>

我想隐藏<li>带有 class="hidden" 的标签

我试过:

ul {
list-style: none;
}



li.hidden:first-child:nth-last-child(2),
li.hidden:first-child:nth-last-child(2) ~ li {
	display: none;
}

li.hidden:first-child:nth-last-child(3),
li.hidden:first-child:nth-last-child(3) ~ li {
	background-color: blue;
}
<ul>
<li class="hidden">1</li>
<li>2</li>
<li class="hidden">3</li>
<li>4</li>
</ul>

有没有办法选择性地检测和更改 <li> 的 CSS 样式?根据 <li> 的数量使用“隐藏”类标记带有“隐藏”类的标签而不影响 <li>没有“隐藏”类的标签?

最佳答案

我稍微尝试了一下。我似乎无法在这方面上课,也许比我更了解 CSS 的人可以让它继续下去,但似乎 nth-of-type 和 last-child 与你想要做的事情有细微差别。

除此之外,在不使用类的情况下,您可以在某种程度上依靠不同的 DOM 元素。希望这足以让您在此基础上构建或让其他人添加到此,但无论如何这应该是一个好的开始。

当您删除一个列表项使其只有 3 个时,所有 3 个的背景颜色都将为蓝色。当您减少到 2 里时,它们就会消失。 1 个、4 个或更多个 li 的实例,它们将正常显示。

由于 nth-last-child 期望参数是last child,因此通过指定 nth-last-child(2)nth-last -child(3) 您期待元素的正好 2 或3 个实例,因为这是从后向前计算子项。

当与 :first-child 连接时,我们正在寻找同时末尾的第二个(或第三个)元素第一个元素的任何元素。

如果满足该条件,则意味着该元素恰好有 2(或 3)个实例。

要获取中间的所有元素,请使用通用兄弟组合器 (~)

要了解有关此的更多信息,您可以查看此站点 [ https://alistapart.com/article/quantity-queries-for-css/ ] 更深入地解释了它,但我在下面列出了一个基本示例。

希望对您有所帮助!

<!doctype html>
<html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <style type="text/css">

        li:nth-last-child(2):first-child, 
        li:nth-last-child(2):first-child ~ li {
            display: none;
        }

        li:nth-last-child(3):first-child, 
        li:nth-last-child(3):first-child ~ li {
            background-color: blue;
        }

    </style>
</head>

<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>
</body>

关于html - 根据特定类的 sibling 调整 div 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56320217/

相关文章:

css - 停止跨越 2 行的导航菜单

javascript - 使用 jQuery 获取通过 DOM 操作插入的表单元素的值

html - Chrome/Chromium 中的拉伸(stretch)图像在 Firefox 和 Opera (CSS/HTML) 中是正常大小

javascript - 元素离开屏幕

javascript - 如何使 CSS 微调器中的文本居中?

html - 正确的 CSS 样式嵌套元素

css - 菜单在手机屏幕外显示

css - 当我为 UL 设置背景图像时,为什么当子元素已经设置了这些设置时我必须设置宽度和高度?

jquery - 使用 LI 下面的 div 类调用 jQuery .on click 函数