Strange things with negative margins on tables

The question is not very short, but it is easy to understand.

Here is jsFiddle

I have two nested tables, for example:

enter image description here

Here is the markup:

<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> 

First strange thing

Then I want to add a negative horizontal border to the inner table:

 .inner { margin: 0 -10%; } 

The expected result looks something like this:

enter image description here

But instead, I get the following:

enter image description here

The problem can be solved by putting the internal table in the 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> 

Second strange thing

If I set a negative horizontal marker -10px (previously we used percentages, not pixels), then in addition, so that the table moves only to the left (as in the first case), it reduces the width blue:

 .inner { margin: 0 -10px; } 

enter image description here

Questions

  • Why do both of these strange things come about?

  • What is the way to solve it? Is it good practice to just use a wrapper like me, or should I use a different, smarter way?

+5
source share
1 answer

If the main table width:100%; , it will expand completely, and the internal table will take 100% for reference. negative margin will not expand it until the content does this. it will work if: https://jsfiddle.net/md2tx2d4/2/

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

or if you let him live without breadth and let him grow out of his content

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

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

+3
source

Source: https://habr.com/ru/post/1244161/


All Articles