官术网_书友最值得收藏!

  • Mastering CSS
  • Rich Finelli
  • 416字
  • 2021-07-08 09:45:46

The box model

The box model defines how wide and tall elements on a page will be. To determine the horizontal space an element occupies, you add up the content + padding-left + padding-right + border-left + border-right + margin-left + margin-right:

So let's take a look at this in practice by looking at the h1 on our site, which is the blue text that says, "Old Chompy".

Here is the ruleset that makes this headline look the way it does:

h1 { 
  font-size: 40px; 
  line-height:1.4; 
  font-weight: bold; 
  color: #0072ae 
} 

Let's add in the following properties to give it a width, padding, border, and margin. As well as a noticeable background-color:

h1 { 
  font-size: 40px; 
  line-height:1.4; 
  font-weight: bold; 
  color: #0072ae 
background-color: black;
width: 300px;
padding: 50px;
border: 10px solid blue;
margin: 50px;
}

Here's what our headline looks like now. One big box:

So those 5 properties that contribute to this element's box model are now in place; looking at the browser in the preceding screenshot, this h1 really looks like a box. We can see the border of 10px, the margin, which is outside the border, is 50px, and the padding, which is between the border and the text, is 50px. Then the width inside the padding is 300px. So this element's width is actually 300 + 20 + 100 + 100, which adds up to a total size of 520px. So even though we said the width is 300px by defining the width property in our CSS file, the true space this element occupies is 520px.

Now, that is the traditional box model. I can modify this traditional box model using the box-sizing property with the border-box value. So let's use the box-sizing property and see how that affects the site. Add the property and value to the bottom of the h1 declaration block, as shown here:

h1 { 
  font-size: 40px; 
  line-height:1.4; 
  font-weight: bold; 
  color: #0072ae 
background-color: black;
width: 300px;
padding: 50px;
margin: 50px;
border: 10px solid blue;
box-sizing: border-box;
}

As illustrated in the following screenshot, border-box will include essentially subtract the padding and border from the width and height calculation. If I use 300px as my width, the border of 20px and the padding of 100px will be subtracted from the 300px I specified. This is a more intuitive box model and it is compatible with Internet Explorer 8 and higher, as well as all other major browsers. The final horizontal space this element now occupies goes from 520px to 400px.

主站蜘蛛池模板: 鄱阳县| 广东省| 上栗县| 海阳市| 武川县| 玉溪市| 德化县| 壤塘县| 昌图县| 鄂温| 大庆市| 监利县| 合江县| 乌什县| 姜堰市| 常宁市| 永平县| 台南县| 新巴尔虎右旗| 宁晋县| 灌云县| 淮阳县| 砚山县| 保康县| 莱阳市| 蒙城县| 长岭县| 类乌齐县| 精河县| 绥阳县| 安丘市| 衡水市| 康定县| 苏尼特左旗| 南澳县| 双辽市| 平塘县| 乐都县| 榆林市| 连州市| 霍邱县|