views:

31

answers:

6

problem with width:50% when border != none

take a look http://jsfiddle.net/5nYSf/

result should be like this

alt text

+1  A: 

The trick is, border and margin are not included in height/width calculation. So, if you have element with width 100px, border 2px and left margin 10px, the 114px of horizontal space will be taken up. (Border is counted twice: left and right.) IIRC, padding is not included too, but I'm not sure about that.

There're several options to solve this. You can have width:49% on both elements or width:50% on first and make second to take up the rest.
If both elements must take exactly equal space, you can include each in its own div. Those divs will have no border/margin/padding and take up exactly 50% of space and border will be specified on inner element.

The last method in action:
http://jsfiddle.net/5nYSf/35/

Nikita Rybak
A: 

Border is in addition to the defined width, so 50% + 50% + 3px border (on both sides) ends up being 100% + 12px, which is 12px bigger than the containing element (100%). Try using 49% or some other measurement that will leave 12px for the border.

bdukes
A: 

Actually, the code you provided on jsFiddle wouldn't output that image even if width:50% and border != none was working properly. The two boxes would appear side-by-side with no margin around them whatsoever.

The closest (quick) workaround is to set margin:-3px to account for the border. Remember, borders are applied outside the container by most models ... so applying a 3px-wide border around your containers makes them wider than 50%, which is why they are out of alignment.

EAMann
A: 

Don't forget to factor in those margins (to show up light grey areas) and that you can't use height:100% for the same reasons you can't use width:50% (as described by others here)

lnrbob
A: 

the border expands the box.

50% + border > 50%

you have to decrease the width:

.attachments {
    height:80px;    
    background-color:#E4E4E4;
}

.attachments span {
    display:inline-block;
    height:100%;
    width:48%;
    background-color:#9FB9CA;
    border:3px #879AA8 solid;
}
revaxarts
+1  A: 

You can put two elements beside each other that are 50% wide, then you can put another element inside each that has to margin and border: http://jsfiddle.net/5nYSf/47/

Guffa