简体   繁体   中英

problem with width:50% when border != none (CSS)

problem with width:50% when border != none

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

result should be like this

替代文字

你可以将两个元素放在50%宽的彼此旁边,然后你可以在每个元素里面放置一个边距和边框: http//jsfiddle.net/5nYSf/47/

If your borders are a fixed width you could substract the border lenght from your element width using the calc() function in your CSS.

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

.attachments span {
float:left;
height:100%;
width:calc(50% - 6px);
background-color:#9FB9CA;
border:3px #879AA8 solid;
}

http://jsfiddle.net/5nYSf/277/

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/

There is a easy way: add { box-sizing: border-box; } in .attachments and the 50% width will contain the border too

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.

不要忘记考虑这些边距(显示浅灰色区域)并且你不能使用高度:100%因为你不能使用宽度的原因:50%(如其他人所述)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM