響應式網頁設計簡單入門


 

Overview:

構造基本的HTML頁面

動態加載樣式表

Viewport

字體縮放

側邊欄

導航菜單

圖片自適應

其他

總結

 

說到響應式網頁設計(Responsive web design),最近在谷歌加上碰到個奇葩貼子,通過一個原始到無法再簡單的網頁Motherfucking Website及滿屏幕的fuck道出了網頁設計的真諦,這孩子不是個激進分子就是個報復社會型的貨沒錯,雖然整篇文章就像是潑婦罵街,但我特么是笑着讀完的。。

統計了下全文共用Fuck (包括fucking) 33次,shit (包括shitty)16次,Motherfucker 8次,創下我所閱讀的技術類文章里面臟話之最。

文章表達的中心思想就是最后的那句引用"最好的設計是盡量少的設計"。最重要的是我意識到平時我們都忽略了一個常識:一張未經加工的原始HTML文檔就已經是響應式的了,根本不用什么CSS media屬性或者指定任何樣式。

通過查看HTML代碼發現作者果然留下了一些信息,於是在twitter上找到他表達了我對他的膜拜之情以及想把如此精華的文章翻譯成中文的意願。作者很爽快地答應了23333~~(X___X)~~。

於是就有了同樣奇葩的中文版本:媽逼的網站,原文的精髓可能由於我自身對這類表達的駕馭的不夠而丟失了一些,但多少還是能夠方便嫌英文閱讀麻煩的同學們圍觀的了。

 

當然以上全是扯淡,一如作者所指出的,相當諷刺。

回到正題,各種屏幕尺寸滿天飛的時代如何讓網站自適應的究極解決方案:響應式設計(Responsive Design)。

構造基本的HTML頁面

一個簡單的博客頁面

始終覺得再多口水都沒有一個生動鮮明的例子來得實在,下面通過對一個普通HTML頁面的改造來體驗什么是響應式設計及如何達到。

下面構造一個基本的HTML頁面,它包含網站導航菜單,正文,圖片,側邊欄,表格式的布局以及頁腳信息。是個非常完整而中庸的布局,幾乎是常見的博客版面。

 

<html>
    <head>
        <title>
            Responsive Design Example
        </title>
        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <div id="main">
            <nav>
                <ul>
                    <li>
                        <a href="#">Home</a>
                    </li>
                    <li>
                        <a href="#">Articles</a>
                    </li>
                    <li>
                        <a href="#">Gallery</a>
                    </li>
                    <li>
                        <a href="#">Forum</a>
                    </li>
                    <li>
                        <a href="#">About</a>
                    </li>
                </ul>
            </nav>
            <aside>
                <ul>
                    <li><a href="#subtitle1">item1</a> </li>
                    <li><a href="#subtitle2">item2</a></li>
                    <li><a href="#subtitle3">item3</a></li>
                    <li><a href="#subtitle4">item4</a></li>
                    <li><a href="#subtitle5">item5</a></li>
                </ul>
            </aside>
            <section class="post">
                <article>
                    <h1>
                        Sample Title
                    </h1>
                    
                    <p></p>
                    
                    <section class="grid">
                        <div class="item">
                            #1
                        </div>
                        <div class="item">
                            #2
                        </div>
                        <div class="item">
                            #3
                        </div>
                    </section>
                    <p></p>
                </article>
            </section>
            <footer>
                <hr>
                <ul>
                    <li><small>Wayou &copy 2013|</small></li>
                    <li><small><a href="mailto:sample@somesite.com">Contact</a></small> </li>
                </ul>
            </footer>
        </div>
    </body>
</html>

 

文章內容填充

剩下文章部分需要填充點內容,正好MS Word有這樣一個產生隨機文章的彩蛋。使用方法是新建一個word文件然后打開輸入" =rand(3,10) " 再回車。其中rand 函數接收兩個參數,第一個表示要產生多少個自然段,第二個表示每段多少行。所以上面回車后我們會得到一篇由3個自然段組成的文章且每段有10行。

 

然后再另存為網頁文件:

最后可以在瀏覽器中通過查看源碼把包含內容的<p>標簽復制到我們的代碼中即可。

同時這里有一個專門產生填充內容的網站Fillerati。可以定義篇幅,作者信息,標題等。

當然以上兩種作法多少有點裝逼與做作的感覺,你完全可以隨便復制點什么東西來作為內容填充的 一_一|||。

填充內容后HTML變成這樣

<section class="post">
    <article>
        <h1>
            Sample Title
        </h1>
        <p>
            Video provides a powerful way to help you prove your point. When you click Online
            Video, you can paste in the embed code for the video you want to add. You can also
            type a keyword to search online for the video that best fits your document. To make
            your document look professionally produced, Word provides header, footer, cover page,
            and text box designs that complement each other. For example, you can add a matching
            cover page, header, and sidebar. Click Insert and then choose the elements you want
            from the different galleries. Themes and styles also help keep your document coordinated.
            When you click Design and choose a new Theme, the pictures, charts, and SmartArt
            graphics change to match your new theme. When you apply styles, your headings change
            to match the new theme. Save time in Word with new buttons that show up where you
            need them.
        </p>
        <section class="grid">
            <div class="item">
                #1
            </div>
            <div class="item">
                #2
            </div>
            <div class="item">
                #3
            </div>
        </section>
        <p>
            To change the way a picture fits in your document, click it and a button for layout
            options appears next to it. When you work on a table, click where you want to add
            a row or a column, and then click the plus sign. Reading is easier, too, in the new
            Reading view. You can collapse parts of the document and focus on the text you want.
            If you need to stop reading before you reach the end, Word remembers where you left
            off - even on another device. Video provides a powerful way to help you prove your
            point. When you click Online Video, you can paste in the embed code for the video
            you want to add. You can also type a keyword to search online for the video that
            best fits your document. To make your document look professionally produced, Word
            provides header, footer, cover page, and text box designs that complement each other.
            For example, you can add a matching cover page, header, and sidebar.
        </p>
        <img class="illustration" src="beauty.png" title="sample pic" alt="beauty" />
        <p>
            Click Insert and then choose the elements you want from the different galleries.
            Themes and styles also help keep your document coordinated. When you click Design
            and choose a new Theme, the pictures, charts, and SmartArt graphics change to match
            your new theme. When you apply styles, your headings change to match the new theme.
            Save time in Word with new buttons that show up where you need them. To change the
            way a picture fits in your document, click it and a button for layout options appears
            next to it. When you work on a table, click where you want to add a row or a column,
            and then click the plus sign. Reading is easier, too, in the new Reading view. You
            can collapse parts of the document and focus on the text you want. If you need to
            stop reading before you reach the end, Word remembers where you left off - even on
            another device.
        </p>
    </article>
</section>

 

最后出來的效果看起來是這樣的:

最后為了讓側邊欄更有意義一點,給文章正文加上一些子標題同時給側邊欄里的元素加上錨點連接可以在文章的子標題間進行導航。

<aside>
    <ul>
        <li>
            <a href="#subtitle1">item1</a>
        </li>
        <li>
            <a href="#subtitle2">item2</a>
        </li>
        <li>
            <a href="#subtitle3">item3</a>
        </li>
        <li>
            <a href="#subtitle4">item4</a>
        </li>
        <li>
            <a href="#subtitle5">item5</a>
        </li>
    </ul>
</aside>
<section class="post">
    <article>
        <h1>
            Sample Title
        </h1>
        <p id="subtitle1">
            <strong> subtitle1 </strong>
        </p>
        <p>
            //正文被省略
        </p>
        <p id="subtitle2">
            <strong> subtitle2 </strong>
        </p>
        <section class="grid">
            <div class="item">
                #1
            </div>
            <div class="item">
                #2
            </div>
            <div class="item">
                #3
            </div>
        </section>
        <p>
            <p id="subtitle3">
                <strong> subtitle3 </strong>
            </p>
            //正文被省略
        </p>
        <p id="subtitle4">
            <strong> subtitle4 </strong>
        </p>
        <img class="illustration" src="beauty.png" title="sample pic" alt="beauty" />
        <p id="subtitle5">
            <strong> subtitle5 </strong>
        </p>
        <p>
            //正文被省略
        </p>
    </article>
</section>

 

基本的樣式

最后加上一些樣式讓整個頁面看起來更正常些。

我們首先去掉body元素的默認外邊距,去掉列表元素前面默認的加點,把菜單里的超連接的下划線也去掉。

 

body {
    margin: 0;
}

li {
    list-style: none;
}

/*navigation bar*/

nav {
    background-color: #333;
}

nav li {
    display: inline-block;
    padding-right: 10px;
}

nav li a {
    text-decoration: none;
    color: white;
    font-size: 1.5em;
}

nav li a:hover {
    color: #DDD;
}

 

再修飾下字體及正文中的三個方塊div以及其他,最后的樣式代碼差不多是這樣的:

html {
    font-family: "microsoft yahei",arial
}

body {
    margin: 0;
}

li {
    list-style: none;
}

/*navigation bar*/
nav {
    background-color: #333;
}

nav li {
    display: inline-block;
    padding-right: 10px;
}

nav li a {
    text-decoration: none;
    color: white;
    font-size: 1.5em;
}

nav li a:hover {
    color: #DDD;
}


/*sidebar*/
aside {
    width: 15%;
    float: left;
}

/*post*/
.post {
    width: 70%;
    margin: 0 auto;
    float: left;
}

 /*grid layout*/
.grid {
}

.grid .item {
    width: 25%;
    height: 150px;
    background-color: #DDD;
    display: inline-block;
}

 /*footer*/
footer {
    width: 100%;
    text-align: center;
    clear: both;
}

footer li {
    display: inline-block;
}

 

其中,因為側邊欄和文章向左浮動了,為了讓頁腳不從最底跳到文章的后面跑到頂部去,要清除頁腳footer兩邊的浮動。

footer{
     width: 100%;
     text-align: center;
     clear:both;
 }

 

最后頁面看起來着不多是這個樣子的

動態加載樣式表

接下來的工作是讓頁面成為響應式的。聽起來覺得是一個全新的領域,但其實平時我們已經在實踐了。比如當指定元素的尺寸時,使用百分比而不是固定像素的大小時,這樣的元素就具備自適應屏幕的能力。最常見的就是指定元素寬度為100%。這樣窗口縮放或屏幕不同時元素始終占據屏幕整個寬度。

一些不太實用的實踐是針對不同屏幕尺寸加載不同的樣式表,這其實相當於為不同尺寸寫不同的樣式表,感覺維護起來不那么方便。

<!-- CSS media query on a link element -->

<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />

代碼來自MDN

通過在引入樣式表時使用media屬性可以控制什么尺寸的屏幕使用哪個樣式表,於是我們可以實現手機訪問時下載手機版樣式,電腦訪問時下載正常樣式。

<link rel="stylesheet" media="screen and (max-device-width: 320px)" href="mobile.css"/>

上面代碼指定如果設備寬度小於320px則調用 "mobile.css"樣式表。

個人覺得這樣為一個站點寫多個分別的樣式表不怎么好,所以這里就不多說了。

Viewport

響應式設計第一件需要做的事情就是在head標簽里指定viewport meta屬性。

Quick Tip: Don't Forget the Viewport Meta Tag》這篇文章很好介紹了Viewport是的緣由及作用。

簡單說來在手機(iPhone Safari)上訪問網頁時它默認會對網頁進行縮放,盡可能多地在屏幕上展示整個頁面的內容。而縮放之后的效果可想而知,一個在電腦上正常展示的頁面被縮放進手機屏幕(通常是240*320)里面后,很難閱讀。

同時由於默認使用縮放,那么你事先設計好的在小屏幕上使用的樣式將不起作用,也就是說手機上展示的是電腦版本的一個縮小版。

我們看MDN上給出的例子截圖。

而在代碼中指定viewport,則可以讓開發者指定網頁視圖區域及縮放比例等。這樣就能修正由瀏覽器自動縮放帶來的影響。

通過我們指定如下代碼:

<meta name="viewport" content="width=device-width, initial-scale=1">

 

表示使用設備寬度(即設備的屏幕寬度)並且縮放指定為1也就是不縮放。

你可能會問這樣指定之后豈不是只能在手機屏幕上顯示網站的部分,比如左上角。這時候正是響應式網頁設計起作用的時候了。如果你專門為小屏幕的訪問進行了優化比如在CSS中使用media屬性(后面會講到),那么當手機訪問時會調用相應的樣式規則,而不會只顯示整個網站的一部分。

字體縮放

指定固定像素的字體大小是我們設計中經常使用的方式,但如果你想字體大小更具彈性的話,最好還是使用相對大小,CSS中比較常用的指定字體相對大小的單位有百分比,em以及CSS3新增的rem。

首先我們指定整個文檔的字體大小為100%。表示頁面字體大小為瀏覽器默認大小的100%。

html {
    font-family: "microsoft yahei",arial;
    font-size: 100%;
}

 

再來看看em與rem。em單位一如他的發音它的基准單位是一個m字母的高度,同時它是指定相對於父級元素的相對大小。也就是說指定為em的元素字體大小是通過對上一層元素的字體大小計算得來的。

<div style="font-size:15px;">
    <p style="font-size:2em;">
        Hello!
    </p>
</div>

 

上面外層div字體大小為15px,同時指定內層p元素字體大小為2em,所以p元素實際的字體大小為15px*2=30px。這點可以通過查看瀏覽器開發工具里面"計算后的樣式"得到證實。

但需要注意的是em有個問題,正因為他會相對於低級元素來計算自己的樣式,所以在層疊很多的情況下,可能出現意料之外的結果。

<div style="font-size:15px;">
    <div style="font-size:2em;">
        <p style="font-size:2em;">
            Hello!
        </p>
    </div>
</div>

 

比如我們期望后面的包含在最外層div中的內容字體大小統一為2em,於是分別在內層div和p上都指定了這一樣式,結果p元素的字體大小其實是乘以了兩次之后的結果 15px*2*2=60px。

為了解決這個問題,於是引入了一個新的單位rem。可以理解為root-em。加了個root前綴表示總是相對於根節點來計算。HTML文檔的根節點當然就是<HTML>標簽了。所以通過rem無論在文檔任何位置指定都可以放心地得到預期的大小。

<div style="font-size:15px;">
    <div style="font-size:2em;">
        <p style="font-size:2rem;">
            Hello!
        </p>
    </div>
</div>

 

如果沒有指定HTML根節點的字體大小,默認為16px,所以這里得到32px。

但rem 不太普適,因為瀏覽器對它的支持力度還不夠,當然如果不考慮太多嵌套情況下em就夠用了。所以我習慣在CSS中使用em來指定字體大小。

 

側邊欄

當縮放瀏覽器窗口到足夠窄(這里是小於560px)時我們可以發現側邊欄與博客文章有重疊,此刻這個窗口寬度就是我們需要寫樣式來干預的時候了。

利用CSS中的media query我們指定當窗口小於630px時將側邊欄隱藏,而讓正文占據整個屏幕寬度也就是設置為100%,並且取消正文的浮動,因為沒有必要了。同時上圖我們可以看到此時的菜單並沒有受到影響所以暫時可以不管。

 

@media only screen and (max-width : 650px) {
    aside {
        display: none;
    }

    .post {
        width: 100%;
        float: none;
        padding: 5px;
        box-sizing: border-box;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
    }
}

 

另外為了不讓subtitle2部分的格子被壓得太小而影響其中的內容(當然現在其中並沒有什么內容),所以此刻我們讓這一部分同樣占100%的寬度,其中每個方塊占32%的寬度。

@media only screen and (max-width : 650px) {
    aside {
        display: none;
    }

    .post {
        width: 100%;
        float: none;
        padding: 5px;
        box-sizing: border-box;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
    }

    .grid {
        width: 100%;
    }

    .grid .item {
        width: 32%;
    }
}

 

 

導航菜單

菜單幾乎是體現響應式設計最直接的一個東西了。判斷一個網站是不是響應式的最好方法就是改變瀏覽器窗口的大小,觀察網站的布局,特別是菜單,在窗口縮小到足夠窄的情況下一個經典的設計是隱藏原來的菜單而只展示由三根橫線組成的圖標。

截圖站點http://residence-mixte.com/

由此我們可以看到一些實現上的端倪,除了常規菜單外,我們需要在HTML代碼中事先擺放好這樣一個橫線圖標元素。

所以改動我們的nav部分的HTML代碼為下面這樣:

<nav>
    <ul>
        <a href="#" id="menuIcon">Ξ</a>
        <li>
            <a href="#">Home</a>
        </li>
        <li>
            <a href="#">Articles</a>
        </li>
        <li>
            <a href="#">Gallery</a>
        </li>
        <li>
            <a href="#">Forum</a>
        </li>
        <li>
            <a href="#">About</a>
        </li>
    </ul>
</nav>

同時補充上樣式:

nav li a:hover,#menuIcon:hover {
    color: #DDD;
}

#menuIcon {
    display: none;
    color: white;
    font-weight: bold;
    font-size: 2em;
    text-decoration: none;
    font-family: arial;
}

 

此刻頁面倒並沒有明顯變化,因為這個圖標開始是不顯示的。

當窗口寬度小於大約490px時,我們的菜單最后一項被擠到了下面一排,所以將500px這個寬度作為分水嶺寫media query代碼。

當屏幕寬度小於500px時,<nav> 里的菜單<ul>標簽不顯示,同時顯示id為menuIcon的菜單圖標<a>標簽。

 

@media screen and (max-width: 500px) {

    nav ul {
        display: none;
        padding: 0;
        margin: 0 5px;
    }

    #menuIcon {
        display: block;
        text-align: right;
        padding: 0 5px;
        border-bottom: 1px #9c9c9c solid;
    }
}

 

這時候我們需要一點javascript代碼來實現點擊三根橫線顯示出來剛才被我們隱藏的菜單,同時再次單擊或者選中一個菜單項后重新隱藏菜單。

<script type="text/javascript">
        $(function() {
            $("#menuIcon,nav ul li").click(function() {
                if ($("#menuIcon").is(":visible")) { //防止寬屏上點擊
                    $("nav ul").toggle(300);
                };
            });
        })
</script>

 

但這個時候菜單不夠完美,最后加上一點樣式美化下。

@media screen and (max-width: 500px) {

    nav ul {
        display: none;
        padding: 0;
        margin: 0 5px;
    }

    #menuIcon {
        display: block;
        text-align: right;
        padding: 0 5px;
        border-bottom: 1px #9c9c9c solid;
    }

    nav ul li {
        width: 100%;
    }

    nav ul li:hover {
        background-color: #555;
    }
}

 

 

目前來說工作得還算滿意,但稍微測試下就會發現個問題:當菜單被點開后又關閉,再將窗口拉寬到足夠寬時,正常模式的菜單不顯示了。

這里給出個不太正規的解決方法,再寫點代碼監聽窗口的resize事件,當窗口大於我們設定的500px時移除我們通過jQuery的toggle函數給菜單<ul> 標簽加上的樣式"style="display:none;",另外也可以通過監聽那個三橫的菜單圖標是否可見也可以達到目的。

$(window).resize(function() {
    if (!$("nav ul").is(":visible")) {
        $('nav ul').attr('style', function(i, style){
            return style.replace(/display[^;]+;?/g, '');
        });
    };
});

 

圖片自適應

普通的圖片是不會自適應屏幕大小的,也就是說圖片太寬的話在手持設備等屏幕較小的情況下會有水平滾動條出現。

最簡單的辦法讓它隨屏幕大小自動縮放就是指定其最大寬度為100%像這樣:

img {
    max-width:100%;
}

 

 

其他

再來處理窗口足夠小的時候那個表格式布局的三個方框。

可以看到窗口很窄的時候這三個div被擠壓得很厲害,所以假設窗口小於420px時,我們讓它們各自獨立一行,占滿整個窗口寬度。

@media screen and (max-width: 420px) {
    .grid .item {
        width: 100%;
        margin-bottom: 5px;
    }
}

 

總結

本文中很多例子不是很恬當,僅用於演示教學,請輕噴。比如將菜單變成圖標顯示時上面例子是在500px為分水嶺寫的media queries,但我們知道500px其實還是很寬的,是足以容下一般長度的菜單正常顯示的,只是在一般手機屏幕寬度480px 或320px,所以針對這個寬度來寫media query更具實際意義。還有就是側邊欄,上面例子中使用的百分比寬度,其實側邊欄可以給個固定寬度,並且上面例子中沒有考慮到側邊欄里的文字很長的情況。沒有考慮到老版本IE不支持media query的情況。這些是例子中不足的地方。但作為演示還是達到了我講解的目的。

 

示例代碼ResiponsiveDesign.zip

 

參考與擴展閱讀:

  1. 1.Responsive Web Design Guidelines and Tutorials
  2. 2.一個響應式頁面測試站點
  3. 3.Using the viewport meta tag to control layout on mobile browsers
  4. 4.Responsive Web Design: What It Is and How To Use It
  5. 5.viewport 相關
  6. 6.Responsive Design with CSS3 Media Queries 的系列文章
  7. 7.How To Create A Responsive Navigation
  8. 8.Adventures in Responsive Navigation


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM