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

html - What is the difference between border-box and content-box in CSS?

What is the difference between border-box and content-box in CSS? I am not clearly understand between these two boxes. For example, box-sizing:border-box; and box-sizing:content-box; The output of the two styles look similar.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

While box-sizing: border-box; uses the box-model that people have come to associate with Internet Explorer, where the dimensions of the padding and border are included in the element’s dimensions. enter image description here (image source)

Example:

enter image description here (image source)

Demo Added.

$("#content").on("click", function() {
  $("*").css("box-sizing", $(this).text());
});

$("#border").on("click", function() {
  $("*").css("box-sizing", $(this).text());
});
.parent {
  width: 50%;
  border: 5px solid #E18728;
  float: left;
}

.child {
  width: 90%;
  padding: 20%;
  border: 4px solid black;
  margin: .5em auto;
}

.twins {
  width: 50%;
  padding: 1em;
  border: 4px solid black;
  float: left;
}


/* styling for Pen, not related to box-sizing or layout */

body {
  font-family: sans-serif;
  font-size: 1.1em;
}

.buttons {
  margin-bottom: .5em;
}

p:not(.intro) {
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
  <p class="intro">Click the <code>border-box</code> button to fix the layout with the power of Box Sizing!</p>
  <button id="content">content-box</button>
  <button id="border">border-box</button>
</div>
<div class="parent">
  <p>Parent div with 50% width.</p>
  <div class="child">
    <p>Child div with 90% width, 4px black border, and 20% padding </p>
  </div>
  <div class="twins">
    <p>Child div with 50% width, 4px black border, and 1em padding</p>
  </div>
  <div class="twins">
    <p>Child div with 50% width, 4px black border, and 1em padding</p>
  </div>
</div>

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

...