--- tags: CSS,六角筆記王 title: CSS - 內容寬度怎麼變來變去? 了解 width 與 max-width / min-width --- # CSS - width 與 max-width / min-width 寬度,最大寬度,最小寬度,都是寬度,而它們有甚麼不同之處? ## ▶ 單一使用寬度屬性 ### ✏ width - 顧名思義,就是某個元素內容的寬度 - 會被最大 / 最小寬度影響,可以設定 CSS 在父層或是本身 - 若設定最大 / 最小寬度在父層,則會受到父層影響 - 若設定最大 / 最小寬度在本身,則會先受到自己影響 - 由於寬度固定,視窗縮放時,低於該寬度會產生 X 軸 ```sass // 固定寬度 .box { width: 500px; } ``` ### ✏ max-width - 最大寬度,限制內容的最大寬度在某個值 - 若當前寬度與最大寬度相同,看起來寬度相同 - 但在縮放瀏覽器視窗時,擁有最大寬度的元素會自動縮小 ```sass // 最大寬度 .box2 { max-width: 300px; } ``` ### ✏ min-width - 最小寬度,限制內容的最小寬度在某個值 - 若當前視窗寬度與最小寬度相同,看起來寬度相同 - 若當前視窗寬度大於最小寬度,且父層為區塊元素,寬度則與視窗寬度相同 - 視窗縮放時,會依據最小寬度卡住不變化,進而產生 X 軸 ```sass // 最小寬度 .box3 { min-width: 300px; } ``` ## ▶ 混和使用寬度屬性 若將它們混合使用會有怎麼的結果? ### ✏ max-width 與 width - 最大寬度被設定成 300px,但內容設定為 500px - 高於最大寬度則會被限制,因此內容被影響 - 實際看到為 300px 寬 ```sass // 最大寬度低於內容寬度,以最大寬度為主 .box4 { max-width: 300px; width: 500px; } // 最大寬度高於內容寬度,以內容寬度為主 .box5 { max-width: 1000px; width: 500px; } ``` ### ✏ min-width 與 width - 若寬度滿足最小寬度,則以寬度為主,不會自動調整 ```sass .box6 { min-width: 300px; width: 500px; } ``` - 若寬度不足最小寬度,則以最小寬度為主並固定寬度,不會自動調整 - 若視窗寬度低於寬度或者最小寬度,會產生 X 軸,寬度卡住不變 ```sass .box7 { min-width: 1000px; width: 500px; } ``` 綜合以上觀察: - 若有最小寬度且低於內容寬度,以內容寬度為主,寬度固定 - 若有最小寬度且高於內容寬度,以最小寬度為主,寬度固定 - 若有最大寬度且低於內容寬度,以最大寬度為主,視窗縮放時會自動延伸 - 若有最大寬度且高於內容寬度,以內容寬度為主,視窗縮放時會自動延伸 - 若同時有最大與最小寬度時,以最小寬度為主 - 若最小寬度低於內容寬度,以內容寬度為主 - 其他條件與上述條件相同 ## 範例連結 [範例連結](https://codepen.io/hsuan333/pen/wvdEOYg) <iframe height="300" style="width: 100%;" scrolling="no" title="六角筆記王 - CSS - width 與 max-width / min-width" src="https://codepen.io/hsuan333/embed/wvdEOYg?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/hsuan333/pen/wvdEOYg"> 六角筆記王 - CSS - width 與 max-width / min-width</a> by Vic (<a href="https://codepen.io/hsuan333">@hsuan333</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## 額外補充 - 媒體查詢寬度,指得是瀏覽器當前視窗的寬度。 ## 參考來源 > 1. [CSScoke - min-width & max-width - 金魚都能懂的CSS必學屬性](https://ithelp.ithome.com.tw/articles/10252194)
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.