2012-05-04 100 views
2

如果我有<div> s在<td>之内,我可以选择每个吗?在td中选择div

例如,我想让第一个浮动左边,第二个浮动右边。有可能只使用CSS?

.divE:first-child { float:left; } 
.divE:last-child { float:right; } 

HTML

<table id="myTbl" cellpadding="0" cellspacing="0"> 
    <tr> 
     <td> 
     <div class="red">asdasd</div> 
     <div class="divE"></div> 
     <div class="divE"></div> 
     content 
     </td> 
    </tr> 
</table> 
+0

对于一个特定类的第一个孩子,你可以检查HTTP:// stackoverflow.com/questions/6447045/css3-selector-first-of-type-with-class-name。但是,如果所有表格单元格都包含相似的结构,则可以尝试使用nth-child(n),如下面的答案中所述。 – Adonais

回答

1

是的,它是:)

您可以通过使用相邻兄弟选择定义,当潜水类的DIV紧随另一个DIV设置.divE类为float,默认情况下离开,然后你就可以潜水类的,就应该浮动权是这样的:

.divE { 
    float:left; 
} 

.divE + .divE { 
    float: right !important; 
} 

但不是很容易只是给的div每一个ID,然后设置彩车到每个?或者只是将.floatRight或.floatLeft类应用于div,然后更改这些类的浮点数?这样你可以重用这些类。

如果你改变了你的HTML:

<table id="myTbl" cellpadding="0" cellspacing="0"> 
<tr> 
    <td colspan="3" width="25%"> 
    <div class="red">asdasd</div> 
    <div class="divE floatLeft"></div> 
    <div class="divE floatRight"></div> 
    content 
    </td> 
</tr> 

并添加CSS是这样的:

.floatLeft { 
float: left; 
} 

.floatRight { 
float:right; 
} 
1

你可以试试这个:

:nth-child(2)

但你用CSS3工作,所以一定要检查这取决于谁是你的浏览器兼容性需要使用您的网站:

http://caniuse.com/#search=nth

0

:nth-child是神奇的。

td div.divE { 
    float: left; 
} 

td div.divE:nth-child(2n) { /* all even divs */ 
    float: right; 
} 

/* or just use "even" */ 
td div.divE:nth-child(even) { 
    float: right; 
} 

适用于所有真实的浏览器。意思是,没有IE8和下。

更多信息:http://css-tricks.com/how-nth-child-works/

0
在这种情况下 :first-child

将不得不<td>下是选择工作的第一个元素(这是不是<div class="red">所以.red:first-child将工作)

,您可以改用:nth-child

.divE:nth-child(2) { float:left; } 
.divE:nth-child(3) { float:right; } 
0

我已经添加了div元素到html,它的工作原理。

CSS

.divE:last-child { color:red; } 
.divE:first-child { color:blue; } 

HTML

<td> 
<div class="red">asdasd</div> 
<div><div class="divE">blue</div></div> 
<div class="divE">red</div> 
content 
</td> 
0

使用:first-child选择的组合和sibling selector让您针对第二div像这样:

.red{ 
    float: left; 
} 
.divE{ 
    float: left; //this is for the second .divE 
} 
.red + .divE{ 
    float: right; //this is for the first .divE 
} 

这样的解决方案作品从IE7起。

+0

它甚至不是一个组合,只是“兄弟姐妹” – skip405