2016-03-01 22 views
5

這個問題不是很短,但很容易理解。桌上有負邊距的奇怪東西

這裏是jsFiddle

我有兩個嵌套表,這樣的:

enter image description here

下面是標記:

<table class="outer"> 
    <tr> 
    <td></td> 
    <td> 
     <table class="inner"> 
     <tr> 
      <td></td> 
      <td></td> 
      <td></td> 
     </tr> 
     </table> 
    </td> 
    <td></td> 
    </tr> 
</table> 

<style> 
table, tr, td { 
    border: 1px solid black; 
    border-collapse: collapse; 
} 

table { 
    width: 100%; 
} 

.outer { 
    height: 100px; 
} 

.inner { 
    background-color: #ccc; 
    height: 50px; 
} 
</style> 

首屆奇怪的

然後,我想添加一個負面的hor izontal緣至內表:

.inner { 
    margin: 0 -10%; 
} 

預期輸出是這樣的:

enter image description here

但是,相反,我得到這個:

enter image description here

問題可能通過將內表放置在div中來解決:

<!-- outer table --> 
    <div class="wrapper"> 
    <table class="inner-wrapped"> 
     <tr> 
     <td></td> 
     <td></td> 
     <td></td> 
     </tr> 
    </table> 
    </div> 
<!-- outer table --> 

<style> 
.wrapper { 
    margin: 0 -10%; 
} 

.inner-wrapped { 
    background-color: rgb(0,200,0); 
    height: 50px; 
} 
</style> 

如果設置了負臥式保證金-10px(以前我們使用的百分比,而不是像素)第二奇怪的東西,然後在另外的那個表(在第一種情況等)只能移動到左側,它sigifically在寬度減少:

.inner { 
    margin: 0 -10px; 
} 

enter image description here

這些問題

  • 爲什麼這兩個事情都會發生?

  • 什麼是解決它的方法?像我一樣簡單地使用包裝是一種好的做法,還是我應該使用另一種更聰明的方式?

+0

在Chrome督察長,看看嵌套的盒子。 (白色橙色和綠色),描述寬度,填充和邊距,這將更有意義 – Ibu

+0

因爲['table-layout:auto'](https://www.w3.org/TR/CSS21/tables。html#auto-table-layout)沒有完全由規範定義,它取決於實現。瀏覽器試圖考慮內容,但在你的情況下,這會導致大量的循環定義。不要依賴結果。如果你想要一個明確的算法,你可以試試['table-layout:fixed'](https://www.w3.org/TR/CSS21/tables.html#fixed-table-layout)。 – Oriol

+0

@Oriol謝謝,有趣 –

回答

3

如果主表是width:100%;,它將一直擴展,內表會以最初的100%作爲參考。只要沒有內容要求,負利潤率就不會擴大。 它會工作,如果:https://jsfiddle.net/md2tx2d4/2/

.inner { margin:0 -10%; width:120%;} 

,或者如果你讓它生活在沒有寬度,讓它從其內容

table { } 
td {width:200px;/* instead real content missing here */} 

https://jsfiddle.net/md2tx2d4/1/