CSS 之 width 與 max-width 差異

栏目: CSS · 发布时间: 6年前

内容简介:對 Element 設定WebStorm 2019.1.3Safari 12.1.1

對 Element 設定 width ,這問題不大,但 RWD 出現後, width 就面臨的重大挑戰,因此出現了 max-width ,但這兩者有什麼差異呢 ?

Version

WebStorm 2019.1.3

Safari 12.1.1

CSS 3

Chrome

CSS 之 width 與 max-width 差異

widthmax-width 小於 container,則視覺上兩者沒有差異。

CSS 之 width 與 max-width 差異

widthmax-width 大於 container 時,就可明顯看出兩者差異。

HTML

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CSS Lab</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h2>width: 500px</h2>
  <div class="general width">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias amet architecto asperiores aut cum distinctio fugiat fugit harum hic incidunt magni maiores minus nemo, officiis quae quaerat quis reprehenderit temporibus?
  </div>
  <h2>max-width: 500px</h2>
  <div class="general max-width">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias amet architecto asperiores aut cum distinctio fugiat fugit harum hic incidunt magni maiores minus nemo, officiis quae quaerat quis reprehenderit temporibus?
  </div>
</body>
</html>

兩個 <div> 內文完全一樣。

CSS

style.css

.general {
  margin: auto;
  border: 3px solid #f00;
}

.width {
  width: 500px;
}

.max-width {
  max-width: 500px;
}

第 1 行

.general {
  margin: auto;
  border: 3px solid #f00;
}

兩個 <div> 的 margin 都使用 auto ,表示若 element 寬度小於 container,則 element 將 水平置中 ,兩側將平分 container 剩餘寬度。

第 6 行

.width {
  width: 500px;
}

.max-width {
  max-width: 500px;
}

widthmax-width 都設定 500px

  • 若 element 寬度小於 container,則兩者沒有差異
  • 若 element 寬度大於 container, width 會有使內容 overflow,但 max-width 則會使內容自動換行

Conclusion

  • 一般來說,在 RWD 世界 max-widthwidth 好用,會隨著 container 寬度自動換行,而不是 overflow 產生 scrollbar 或隱藏內容

Reference

w3schools.com , CSS Layout - width and max-width

MDN , width

MDN , max-width


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Domain-Driven Design

Domain-Driven Design

Eric Evans / Addison-Wesley Professional / 2003-8-30 / USD 74.99

"Eric Evans has written a fantastic book on how you can make the design of your software match your mental model of the problem domain you are addressing. "His book is very compatible with XP. It is n......一起来看看 《Domain-Driven Design》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具