2014-08-29 104 views
0

讓我們得到開門見山,我創造了這個例子跨越,以更好地讓我的觀點:影響父只

Demo Here

HTML: 表1

<table class="testClass"> 
    <tr> 
     <td>Inner table 
      <table> 
       <tr> 
        <td>Hello</td> 
        <td>Testing testing</td> 
        <td>Bye</td> 
       </tr> 
      </table> 
     </td> 
    </tr> 
</table> 
<br /> 
<br /> 
<br />Table 2 
<table class="testClass"> 
    <tr> 
     <td colspan="3">stuff</td> 
    </tr> 
    <tr> 
     <td>Left</td> 
     <td>Middle</td> 
     <td>Right</td> 
    </tr> 
</table> 

CSS:

table { 
    border: 2px solid red; 
    width: 100%; 
} 
td { 
    border: 2px solid blue; 
} 
/* Relative CSS */ 
.testClass tr:last-child td:nth-child(1) { 
    width: 15px; 
} 
.testClass tr:last-child td:nth-child(2) { 
    width: auto; 
} 
.testClass tr:last-child td:nth-child(3) { 
    width: 15px; 
} 

所以我們有2個表,兩個表都是相同的類。 Table 1有一個表格,其中Table 2沒有。

我發現這個問題是使用我創建的CSS,我無法停止受影響的子表(內表).testClass的樣式。我認爲:not()可以使用,但我無法找到解決方案,我覺得這應該不是那麼難。

是否有可能隻影響從父進入子表的樣式中的父親?

注意:只能更改CSS而不是HTML。 CSS3可以使用!

我希望這是有道理的,如果我需要使它更清晰,請發表評論。

+0

爲什麼不使用類似'.testClass> tr ...'的東西來設計只有可怕ct孩子?像[this](http://jsfiddle.net/urryfof5/2/)。 – Harry 2014-08-29 09:51:00

+2

@Harry這應該是'.testClass> tr,。testClass> tbody> tr',因爲大多數現代瀏覽器都會自動插入表格主體。 – feeela 2014-08-29 09:53:17

+0

@feeela:是的,好點。 – Harry 2014-08-29 09:55:50

回答

2

選擇第一級孩子並應用它。

.testClass > tbody > tr:last-child > td:nth-child(1) { 
     width: 15px; 
    } 
    .testClass > tbody > tr:last-child > td:nth-child(2) { 
    width: auto; 
    } 
    .testClass > tbody > tr:last-child > td:nth-child(3) { 
     width: 15px; 
    } 

DEMO

+0

這阻止了表2獲取樣式[Demo](http://jsfiddle.net/urryfof5/5/) – Ruddy 2014-08-29 09:55:36

+1

Mate,請參考feeela在問題中的評論,'tbody'也是必需的,因爲大多數瀏覽器都會添加它默認。 – Harry 2014-08-29 10:18:45

+1

我已經更新了我的答案。謝謝Harry。 – 2014-08-29 10:21:15

0

您可以添加樣式聲明樣

table table { border: none; } 

從父table -declaration覆蓋樣式。這樣,沒有嵌套的表格會有邊框。 td同樣適用。

另一個解決方案是:

table:not(.testClass) { 
    border: 0px none; 
} 

這消除邊界爲做應用了testClass所有表。我測試並看到了這項工作(在下面的小提琴的另一個版本中)。

這裏有一個撥弄你的代碼有兩個附加聲明,消除邊界內部表: http://jsfiddle.net/erlingormar/bk6m4w5d/#base

0

也許是這樣的:http://jsfiddle.net/urryfof5/7/

基本上你調用從最後一個子表body和add>,所以它不會影響裏面的嵌套表格:

body > table:last-child (and follow it with your css) 
+0

請在您的答案中包含代碼並解釋您所做的事情。哦,知道,這是用身體,對不起,我沒有看。頁面上有大量表格,這是行不通的。 – Ruddy 2014-08-29 10:00:19