Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...