示例图片:
元素的组成结构:
content + margin + border + padding
width: 100%时:
width = screenWidth + padding + margin + border
contentWidth = screenWidth
width: auto时
width = screenWidth
contentWidth = screenWidth - padding - margin - border
♥推荐使用margin:auto
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {margin: 0}
.container {
/* display: none; */
width: 100%;
height: 60px;
padding: 20px;
border: 1px solid blue;
margin: 30px;
background: #aaaaff;
}
.content {
/* display: none; */
width: auto;
height: 60px;
padding: 20px;
border: 1px solid blue;
margin: 30px;
background: #aa33ff;
}
</style>
</head>
<body>
<div class="container">container--> </br>width: 100% = screenWidth + padding + margin + border</br>contentWidth = screenWidth</div>
<div class="content">content--> </br>width: auto = screenWidth</br>contentWidth = screenWidth - padding - margin - border</div>
</body>
</html>
margin:auto 的元素设置margin-right为负值时,元素的宽度将变宽