CSS 基礎(009_Max-width)

原始網址:http://www.w3schools.com/css/css_max-width.asp

翻譯:

CSS Layout - width and max-width


使用 widthmax-widthmargin: auto;

在之前的章節中提到過,塊級元素總是佔據整行(向行左、右無限延伸)。
對塊級元素設置 width 會阻止它向父級容器的邊界延伸。接下來,爲了讓元素在父級容器內居中顯示,我們可以將 margins 設置爲 auto 。元素將會佔據指定寬度,剩餘空間將在兩個 marginsmargin-leftmargin-right) 之間均分:
CSS Layout

<!DOCTYPE html>
<html>
    <head>
        <style>
            div {
                border-color: #4caf50 !important;
                border-width: 3px;
                border-style: solid;
                width: 600px;
                margin: auto;
            }
        </style>
    </head>
    <body>
        <div>This &lt;div&gt; element has a width of 600px, and margin set to auto.</div>
    </body>
</html>

注意:當瀏覽器窗口小於元素的寬度時,以上 <div> 會出現問題。然而,瀏覽器會在頁面上增加一個水平滾動條。
在此情況下,使用 max-width 取代 width 將會改善瀏覽器處理小窗口的方案。這對構建一個適合在小設備上運行的站點是很重要的:
CSS Layout

<!DOCTYPE html>
<html>
    <head>
        <style>
            div {
                border-color: #4caf50 !important;
                border-width: 3px;
                border-style: solid;
                max-width: 600px;
                margin: auto;
            }
        </style>
    </head>
    <body>
        <div>This &lt;div&gt; element has a max-width of 600px, and margin set to auto.</div>
    </body>
</html>

提示:將瀏覽器窗口的大小調整爲小於 600px 時,請查看兩個 divs 的不同!

<div> 分別設置爲 width: 800px;max-width: 800px; 時的比較:
CSS Layout

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章