5

I have divided the screen with many div so they stick one to each other (let say, something like chess-board, but with fields of variable sizes). I set heigth and width using percents (relative to parent container).

Now, when I add border: 1px to the divs, all the layout breaks... I imagine that the border adds 1px to each side, and the solution would be to add some internal border. Can I add somehow such an internal border?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Jakub M.
  • 32,471
  • 48
  • 110
  • 179

4 Answers4

13

You can use box-sizing: border-box to make the border's width part of the width of the element.

.example {
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

Browser support.

thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • /* You forgot -ms for IE*/ -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; – Emilio Yero Jul 23 '12 at 02:05
  • @EmilioYero: No, I didn't. Take a look at the "browser support" link at the end of my answer. IE7 doesn't support it at all, whereas IE8 and higher support it without a vendor prefix. – thirtydot Jul 23 '12 at 02:48
5

Use outline property. Unlike the border propperty it does not "add" to the height or width of the elements. However also unlike the border propeerty you can not have left, right, bottom or left individual properties. Although you can have outline-style, outline-width and outline-color properties.

Outline Refrence

Jawad
  • 8,352
  • 10
  • 40
  • 45
  • @Phil: I am not sure, but I think outline property is well supported even in legacy browsers. I stand to be corrected. – Jawad Jul 19 '11 at 16:48
  • @thirtydot: One thing I found out using CSS reference is that their comptibility department is often wrong. For example I have from personal experience that outline is suppoted in IE8 and above and in FF 3.5 and above. – Jawad Jul 19 '11 at 17:14
  • That link says "buggy" for IE8 and FF 3.5. That means it *does work*, but.. there are bugs which are detailed underneath the compatibility table. – thirtydot Jul 19 '11 at 17:18
1

You can decrease the percentages by 0.5 making them 49.5% EDIT: Outset won't work, thanks @thirty

Phil
  • 10,948
  • 17
  • 69
  • 101
0

Let say, if you have a parent div and many child divs. When you set the height and width as percentages, you'll get them stick to each other. Then when adding border:1px their width will become longer than as it was before. To solve this, I would say that you should have another div after the parent div to prevent resizing width.

Tepken Vannkorn
  • 9,648
  • 14
  • 61
  • 86