Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

html - CSS: Width in percentage and Borders

I've defined widths of the containers in percentage. I'd like to add a border (3px on right side of a width), since container width is in % while the border width is in px, how can I adjust the width of the container?

<div class="wrap">
  <div class="left">...</div>
  <div class="right">...</div>
</div>

.wrap{
    width:100%;
}

.left{
    width:30%;
}

.right{
    width:70%;
}

I'd like to add 3px border on the right side of .left. For example:

.left{
    width:30%;
    border:3px solid #000;
}

Since I have defined width in the %, what is the best way to re-adjust the width of the .left. I can roughly decrease the width to 29%, but I want to do precisely.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the box-sizing: border-box property. It modifies the behaviour of the box model to treat padding and border as part of the total width of the element (not margins, however). This means that the set width or height of the element includes dimensions set for the padding and border. In your case, that would mean the element's width and it's border's width would consume 30% of the available space.

CSS box model

Support for it isn't perfect, however vendor prefixes will catch most if not all modern browsers:

.left {
    width: 30%;
    border: 3px solid #000;

    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;
}

More information can be found on the MDN and Quirksmode.

According to Quirksmode, using the 3 vendor prefixes above (-moz-, -webkit- and -ms-), you get support for all browsers, even IE8.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...