CSS 框大小调整


目录

    显示目录


CSS 框大小调整

CSS box-sizing 属性允许我们将内边距和边框包含在 元素的总宽度和高度。


没有 CSS box-sizing 属性

默认情况下,元素的宽度和高度计算如下:

width + padding + border=元素的实际宽度
height + padding + border=元素的实际高度

这意味着:当你设置元素的宽度/高度时,该元素经常会出现 比您设置的更大(因为元素的边框和填充已添加到元素的指定宽度/高度)。

下图显示了两个具有相同内容的 <div> 元素 指定宽度和高度:

This div is smaller (width is 300px and height is 100px).

This div is bigger (width is also 300px and height is 100px).

上面的两个 <div> 元素最终在结果中具有不同的大小 (因为div2有一个填充 指定的):

例子

.div1 {
  width: 300px;
  height: 
100px;
  border: 1px solid blue; 
}

.div2 {
  width: 300px;
  height: 100px;
  padding: 50px;
  border: 1px solid red;
} 

自己尝试一下 →

<!DOCTYPE html>
<html>
<head>
<style> 
.div1 {
  width: 300px;
  height: 100px;
  border: 1px solid blue;
}

.div2 {
  width: 300px;
  height: 100px;  
  padding: 50px;
  border: 1px solid red;
}
</style>
</head>
<body>

<h1>Without box-sizing</h1>

<div class="div1">This div is smaller (width is 300px and height is 100px).</div>
<br>
<div class="div2">This div is bigger (width is also 300px and height is 100px).</div>

</body>
</html>


box-sizing 属性解决了 这个问题。



使用 CSS box-sizing 属性

box-sizing 属性允许我们将内边距和边框包含在元素的总宽度和高度中。

如果在元素上设置 box-sizing: border-box;,则内边距和边框将包含在宽度和高度中:

Both divs are the same size now!

Hooray!

这是与上面相同的示例,其中 box-sizing: border-box; 添加到两个 <div> 元素:

例子

.div1 {
  width: 300px;
  height: 
100px;
  border: 1px solid blue;
  box-sizing: border-box;
}

.div2 {
  width: 300px;
  
height: 100px;
  padding: 50px;
  border: 1px solid red;
  box-sizing: border-box;
} 

自己尝试一下→

<!DOCTYPE html>
<html>
<head>
<style> 
.div1 {
  width: 300px;
  height: 100px;
  border: 1px solid blue;
  box-sizing: border-box;
}

.div2 {
  width: 300px;
  height: 100px;  
  padding: 50px;
  border: 1px solid red;
  box-sizing: border-box;
}
</style>
</head>
<body>

<h1>With box-sizing</h1>

<div class="div1">Both divs are the same size now!</div>
<br>
<div class="div2">Hooray!</div>

</body>
</html>


由于使用 box-sizing: border-box; 的结果要好得多,因此许多开发人员希望页面上的所有元素都以这种方式工作。

下面的代码确保所有元素都以这种更直观的方式调整大小。许多浏览器已经对许多表单元素(但不是全部)使用 box-sizing: border-box; - 这就是为什么输入和文本区域在 width: 100%; 下看起来不同的原因)。

将其应用于所有元素是安全且明智的:

例子

* {
  box-sizing: border-box;
}

自己尝试一下→

<!DOCTYPE html>
<html>
<head>
<style>
body {
  margin: 0;
}

* {
  box-sizing: border-box;
} 

input, textarea {
  width: 100%;
}
</style>
</head>
<body>

<form action="/action_page.php">
  First name:<br>
  <input type="text" name="firstname" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br>
  Comments:<br>
  &lt;textarea name="message" rows="5" cols="30">
  &lt;/textarea>
  <br><br>
  <input type="submit" value="Submit">
</form> 

<p><strong>Tip:</strong> Try to remove the box-sizing property from the style element and look what happens.
Notice that the width of input, textarea, and submit button will go outside of the screen.</p>

</body>
</html>



CSS 框大小调整属性

box-sizing

定义如何计算元素的宽度和高度:should 它们包括填充和边框,或者不包括