CSS 布局 - 宽度和最大宽度


目录

    显示目录


使用宽度、最大宽度和边距:auto;

正如上一章提到的;块级元素总是占据可用的全部宽度 (尽可能向左和向右伸展)。

设置块级元素的宽度将防止其拉伸 到其容器的边缘。然后,您可以设置 margins 为 auto,使元素在其容器内水平居中。这 元素将占据指定的宽度,剩余空间将被分割 两个边距之间相等:

This <div> element has a width of 500px, and margin set to auto.

注意:上述<div>的问题发生在浏览器窗口打开时 小于宽度 元素。然后浏览器向页面添加水平滚动条。

在这种情况下,使用 max-width 可以改善 浏览器对小窗口的处理。这对于使网站可用时很重要 在小型设备上:

This <div> element has a max-width of 500px, and margin set to auto.

提示:将浏览器窗口大小调整为宽度小于 500 像素,以查看之间的差异 两个div!

这是上面两个 div 的示例:

例子

div.ex1 {
  width: 500px;
  margin: 
auto;
  border: 3px solid #73AD21;
}

div.ex2 {
  max-width: 500px;
  
margin: auto;
  border: 3px solid #73AD21;
}

自己尝试一下 →

<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
  width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}

div.ex2 {
  max-width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>CSS Max-width</h2>

<div class="ex1">This div element has width: 500px;</div>
<br>

<div class="ex2">This div element has max-width: 500px;</div>

<p><strong>Tip:</strong> Drag the browser window to smaller than 500px wide, to see the difference between 
the two divs!</p>

</body>
</html>