0

fiddle

HTML

<div id="a">
    <table id="b">
        <tr><td></td></tr>
    </table>
</div>

CSS

* {
    margin: 0;
    padding: 0;
}

#a {
    background-color: yellow;
}

#b {
    background-color:red;
    height: 50px;
    margin-left: 50px;
    width: 100%;
}

I want the table #b to span from 50px from the left of its container (#a) all the way to the right edge of of #a.

By setting the width to 100% it goes off the page because it tries matching the width of #a. If I omit the width then the table is too small.

Setting the table to display:block and removing the width seems to give the desired behaviour. Is this reliable, or is there another method of achieving the same thing? I'd prefer not to resort to absolute positioning.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 1
    [This post](http://stackoverflow.com/questions/5219175/width-100-padding/5219611#5219611) suggests that `display:block` is reliable cross browser. You could also look at the 'box-sizing' property. I also really like this negative margin approach. http://stackoverflow.com/a/11238699/661447 – jammykam May 21 '13 at 22:35
  • You might also find this interesting http://stackoverflow.com/questions/1260122/expand-div-to-take-remaining-width – Evgeny May 22 '13 at 20:38

2 Answers2

3

You can use the calc() function in CSS like this:

#b {
  width: calc(100% - 50px);
  /* your other stuff */
}

Most browsers support this nowadays. Have a look at caniuse.com to see, which browsers don't.

Example Fiddle

Sirko
  • 72,589
  • 19
  • 149
  • 183
2

One way to do is is to use box-sizing: border-box

* { -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
...
#a {
    ...
    padding-left: 50px;
}

Unlike Sirko's answer, this is will work in IE8+ and not IE9+

Another way is to use conflicting absolute positioning

Evgeny
  • 6,261
  • 8
  • 35
  • 43
  • Interesting. Why would border-box change the width? I know it changes the box-model so the width is calculated differently, but.. I'd expect to still collapse if it did previously. – mpen May 22 '13 at 01:31
  • 1
    @Mark The main change here is not the `border-box`, but applying `padding-left` to `#a` instead of `margin-left` to `#b`! – Sirko May 22 '13 at 06:15
  • @Sirko: Oh! I didn't notice you had moved it. That makes perfect sense now. – mpen May 22 '13 at 15:42
  • 1
    @Mark That's not my answer ,-) But it is just the "old" way of doing such a thing. Clear advantage is, of course, this is the better compatibility with older browsers, which do not understand `calc()`. – Sirko May 22 '13 at 15:50