I have made bars in a waterfall diagram that I want to be look like blocks on each other. They are inline-blocks programmatically set to a width and adjusted sideways by margin-left.
The javascript to set innerHTML is irrelevant in this case, but the minimal CSS and HTML I have experimented on is below. Run this fiddle to see how it looks like:
* { padding:0; margin:0; }
div { display:inline-block; }
table {
width:100%;
white-space:nowrap;
cellpadding:0;
}
td { border:solid 1px black; }
.bar{
margin:0;
border:solid 1px red;
background:yellow;
}
.padOnlyThisCell{
padding:20px;
}
.padNotThisCell{
padding:0;
}
<br>
<table cellspacing="0">
<tr>
<td class='padOnlyThisCell'>
First column
</td>
<td class='padNotThisCell'>
<div class='bar padNotThisCell' style='margin-left:30%; width:30%'><sub> Why does this bar have margin? </sub></div>
<sup> Why does this cell have padding?</sup>
</td>
</table>
<br>
There is an unwanted table cell padding despite padding:0
everywhere but not in the cells of first column where padding is wanted.
What I want is a bar with upper and lower red border touching it's surrounding black border.
It's the same in both Chrome and Firefox: The padding
in the first <td>
affects the other <td>
in the <tr>
. Why? How to change this code to not have space above and under the bar without loosing the padding in first column?
An inner-block is resized to fit it's content that should have the padding.
Change padNotThisCell
on the bar to padThisCell
and it will work:
* { padding:0; margin:0; }
div { display:inline-block; }
table {
width:100%;
white-space:nowrap;
cellpadding:0;
}
td { border:solid 1px black; }
.bar{
margin:0;
border:solid 1px red;
background:yellow;
}
.padThisCell{
padding:20px;
}
.padNotThisCell{
padding:0;
}
<br>
<table cellspacing="0">
<tr>
<td class='padThisCell'>
First column
</td>
<td class='padNotThisCell' style='width:100%;'>
<div class='bar padThisCell' style='margin-left:30%; width:30%'> Bar </div>
</td>
</table>
<br>
Renamed padOnlyThisCell
to padThisCell
because they are now on two places. Naming in code affects thougt. Renaming often is a good programming habit.
The padding of first <td>
does not affect the padding in the other <td>
! To see that I got help from this answer: in Chrome, open up inspector (F12 or right click -> inspect element) and there you can see what's being applied to the element.
What actually happens is that an inline-block
has the ability to shrink the borders to fit its content despite any paddings or margins around. Adding the same padding inside the bar as in the first cell makes a perfect fit.
To be more specific a padding-top:20px
and padding-bottom:20px
in the .bar-rule of css will do (because i'm not shure if the padding otherwise can bug with the width). Also added style='width:100%;'
in the second cell to push the first cell to shrink.