[英]css target first li in a div of many divs
so I have been trying all this stuff with first-child
and everything and none seem to be working. 所以我一直在尝试所有这些东西与
first-child
和一切,似乎没有工作。 If I have a div set up as such: 如果我有这样的div设置:
<div class="content">
<div class="thing">
abd
</div>
<div class="thing">
</div>
<div class="thing">
123
</div>
<div class="thing">
<li class="list" goal="target">
1
</li>
</div>
<div class="thing">
<li class="list">
2
</li>
</div>
<div class="thing">
<li class="list">
3
</li>
</div>
<div class="thing">
<li class="list">
4
</li>
</div>
</div>
what line of css that will be able to target only the first li
element in the .content
div
(the one with the attribute goal="target"
) 什么行的css只能定位
.content
div
的第一个li
元素(属性goal="target"
那个)
now this can be fairly messy and there can be anywhere from 0 to 10 div
s without a li
before the first that contains one. 现在这可能相当混乱,并且在第一个包含一个之前可以有0到10个
div
而没有li
任何地方。
I have tried nearly anything with first-child
, but it always targets every single li
because they are in div
s. 我几乎尝试过任何与
first-child
东西,但它总是针对每一个li
因为它们都在div
。
here is a jsfiddle if you want to try things 如果你想尝试一下,这里有一个jsfiddle
In CSS the format is grandparent parent element child
... and :nth-child
gives you the element the number specified down, so for your case that would be 在CSS中,格式是
grandparent parent element child
......并且:nth-child
为您提供指定数字的元素,因此对于您的情况将是
.content .thing:nth-child(4) li {
/* CSS goes here */
}
In your example .content
is the grandparent, .thing
(the fourth one) is the parent, and of course the li
is the element. 在你的例子中
.content
是祖父母, .thing
(第四个)是父母,当然li
是元素。 Spaces are required for distinguishing in between levels in CSS. 需要空格来区分CSS中的级别。
Here is a working jsFiddle 这是一个有效的jsFiddle
Edit Without it being hard coded it's impossible to select the first li
no matter who it's parent is without javascript. 编辑如果没有硬编码,无论父母是谁没有javascript,都不可能选择第一个
li
。
Here is a jQuery fix: 这是一个jQuery修复:
$('.content').find("li").eq(0).css({ /* CSS goes here */});
Here is a straight javascript fix: 这是一个直接的JavaScript修复:
var elems = document.getElementsByTagName('li')[0];
elems.style.property="value";
OK first things first, goal
is an invalid attribute so you shouldn't be using it. 首先确定,
goal
是无效属性,因此您不应该使用它。 If you need custom attributes you should be using data-attributes 如果您需要自定义属性,则应使用数据属性
In order to target an element by attribute you should be using an attribute selector in your case the following selector would work. 为了按属性定位元素,您应该在您的情况下使用属性选择器 ,以下选择器将起作用。
li[goal="target"]{
/* Your styles go here.*/
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.