2013-03-13 88 views
1

我试图总是选择类“.chartKeyListItem”的第一个元素。它在父级“chartKey”下。所以这对于第一个孩子选择器来说很好,如果它是第一个元素,但是有时我有3个元素,所以我不得不使用第n个选择器(4),这对于那个实例是有效的。但是我的代码应该能够在不破坏对方的情况下处理两者。 (如果两个CSS类都加载进来,因为它的第一个实例将它定位到第一个和第四个“chartKeyListItem”)它是否有办法仅仅选择第一个“.chartKeyListItem”?选择一个类的第一个实例,但不知道父类的位置

此外,chartKeyListItem div的数量并不是确定的,可以是2到20之间的任何值,MinMax标签只会显示一些页面,但CSS需要能够处理它们何时存在以及何时他们是不是......下面

代码: 实例1:

<div class='chartKey'>" 
    <div class='chartKeyListItem'> //Just want to add margin to this one 
    <div class='chartKeyListItem'> 
    <div class='chartKeyListItem'> 
    <div class='chartKeyListItem'> //THIS ONE GETS BOTH CLASSES WHICH I DONT WANT 
</div> 

实例2:

<div class='chartKey'>" 
    <div class='pollResultsMinMaxLabel' style='width:auto;float:left;margin-left:20px;'>Min</div> 
    <div class='pollResultsMinMaxLabel' style='width:auto;float:left;margin-left:20px;'>Max</div> 
    <br/> 
    <div class='chartKeyListItem'> //Just want to add margin to this one 
    <div class='chartKeyListItem'> 
    <div class='chartKeyListItem'> 
    <div class='chartKeyListItem'> 
    <div class='chartKeyListItem'> //This one will get both class too 
</div> 

CSS:

.chartKeyListItem:first-child{ 
    margin-left: 60px !important; 
} 
.chartKeyListItem:nth-child(4) { 
    margin-left: 60px !important; 
} 

回答

2

为此,您需要某种类型的first-of-class选择器,可悲的是我们还没有。但是,可以达到同样的效果:)

.chartKeyListItem { 
    margin-left: 60px !important; 
} 

.chartKeyListItem ~ .chartKeyListItem { 
    margin-left: 0 !important; 
} 

它是如何工作的:你是造型类,然后由该类之前该类的所有实例都在写有0利润率左。你可以找出~如何工作here

+0

这工作......谢谢! – Kierchon 2013-03-13 14:42:54

+0

+1 Andy是对的,你不能**但是瞄准.css-class的第一个实例。所以你必须针对所有其他人。 – 2013-03-13 14:44:17

相关问题