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
598 views
in Technique[技术] by (71.8m points)

html - CSS3 box-sizing property

I don't understand how should I use box-sizing property. Because this:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css"> 
        div.container
        {
            width:10em;
            border:1em solid;
        }
        div.box
        {
            box-sizing:border-box;
            -moz-box-sizing:border-box; /* Firefox */
            -webkit-box-sizing:border-box; /* Safari */
            width:50%;
            border:1em solid red;
            float:left;
        }
        </style>
    </head>
    <body>

        <div class="container">
        <div class="box">1</div>
        <div class="box">2</div>
        </div>

    </body>
</html>

is equivalent to this:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css"> 
        div.container
        {
            width:10em;
            border:1em solid;
        }
        div.box
        {
            width:3em;
            border:1em solid red;
            float:left;
        }
        </style>
    </head>
    <body>

        <div class="container">
        <div class="box">1</div>
        <div class="box">2</div>
        </div>

    </body>
</html>

So when should I use that property and that exactly that do? I used example from w3 http://www.w3schools.com/cssref/css3_pr_box-sizing.asp

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

box-sizing: border-box is most useful when you can't specify an exact content width based on the margins, borders and padding of a box, because you don't know in advance (and can't control) what these values are.

In your first example, if you didn't know how much padding was in the box or how thick its borders were, making it use the border-box model allows you to just set width: 50% to ensure that the box will always take up 50% width of its container, regardless of borders and padding. In the second example, if you had set width: 50% that's the width of the content; the borders and padding would add to it, causing it to actually expand beyond 50% of the width of its container.


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

...