CSS佈局問題集錦

這裏介紹下自己在實踐過程中遇到的一些css佈局的問題,一方面做個備忘,也希望給大家帶來一點幫助。
  • 如何讓div顯示爲整個頁面的高度
    我們有時希望一個container顯示爲整個頁面高度,很容易想到將它的高度設置爲100%,可是實際顯示的效果卻不是我們想要的。我用一張張圖說明原因:

    這裏寫圖片描述

    html和body默認高度都是匹配內容高度的,我們想要讓container的高度和頁面高度一樣,得先把html和body的高度設置爲100%

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>兩列布局</title>
        <style>
            *{
                padding: 0;
                margin: 0;
                -webkit-box-sizing: border-box;
                box-sizing: border-box;
            }

            html, body{
                height: 100%;
            }
            .container{
                height: 100%;
                background-color: #B0B0B0;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="left">我是left</div>
            <div class="right">我是right</div>
        </div>
    </body>
</html>
  • 如何做兩列布局,並且做到等高
    現實中經常見到這種的頁面——左邊是導航鏈接,右邊是內容,當顯然右邊的內容頁的高度會比左邊的導航頁的寬度高,那怎麼讓左邊隨着右邊的高度增加而增加呢?
    其實做到兩點就好了,第一:設置左邊的寬度爲固定值A,float爲left,右邊的div的margin-left爲固定值A;第二:在左邊div和右邊div的css裏分別加上margin-bottom: -2000px;padding-bottom: 2000px; 2000是個很大的值,你可以設得更大。這樣就做到了等高。
    <style>
            *{
                padding: 0;
                margin: 0;
                -webkit-box-sizing: border-box;
                box-sizing: border-box;
            }

            html, body{
                height: 100%;
            }
            .container{
                height: 100%;
                background-color: #B0B0B0;
            }
            .left{
                float: left;
                background-color: #FFFFFF;
                width: 150px;
                margin-bottom: -2000px;
                padding-bottom: 2000px;
                padding-left: 20px;
                padding-top: 20px;
            }
            .left ul li{
                list-style: none;
            }
            .left ul li a{
                text-decoration: none;
            }
            .right{
                margin-left: 150px;
                text-align: center;
                background-color: antiquewhite;
                /*height: 100%;*/
                padding-top: 20px;
                margin-bottom: -2000px;
                padding-bottom: 2000px;
            }
        </style>

查看demo

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