Web自適應佈局那些事兒

前言

最近作了一個項目須要自適應佈局,對於萌新的我,就百度,視頻,書等學習下,概括了實現自適應佈局各類方式,有什麼不足,但願多提意見css

自適應佈局

  • 浮動佈局
  • 定位佈局
  • flex佈局
  • table-cell佈局
  • grid佈局

題目:假設高度已知,請寫出二欄佈局,其中左欄、寬度爲160px,中間自適應

image.png

flex佈局

html結構,大盒子設置flex,裏面設置左右兩個小盒子

<body>
    <section class="box">
        <article class="box-left">
        </article>
        <article class="box-right">
            <h1>hello</h1> 
        </article>
    </section>
</body>
複製代碼

CSS部分

html * {        //去除瀏覽器默認邊距
            margin: 0;
            padding: 0;
        }

        .box {
            display: flex;
            width: 100%;
            // height:100vh;    //高度沒法自適應,遇到內容過多,會溢出盒子,用下面方法替代
            min-height: 100vh;
            
        }

        .box-left {
            width: 160px;
            min-height: 100vh;
            
            background: greenyellow;
        }

        .box-right {
            // 方法一:
            flex: 1;
            // 方法二:
            width: calc(100% -160px);   // 剩餘寬度等於總寬度減去左盒子寬度
            min-height: 100vh;
            background: darkcyan;
        }
複製代碼

float 佈局,基本就css有些地方改動而已

CSS

.box {
            width: 100%;
            min-height: 100vh;
            max-height: 100%;
        }

        .box-left {
            float: left;            //修改地方 
            width: 160px;
            min-height: 100vh;
            max-height: 100%;
            background: greenyellow;
        }

        .box-right {
            min-height: 100vh;
            max-height: 100%;
            background: darkcyan;
        }
複製代碼

定位佈局

CSS

.box {
            width: 100%;
            min-height: 100vh;
            max-height: 100%;
            position: relative;  //修改地方
        }

        .box-left {
            position: absolute;  //修改地方
            left: 0;   //修改地方
            width: 160px;
            min-height: 100vh;
            max-height: 100%;
            background: greenyellow;
        }

        .box-right {
            position: absolute;    //修改地方
            left: 160px;  //修改地方
            right: 0;   //修改地方
            min-height: 100vh;
            max-height: 100%;
            background: darkcyan;
        }
複製代碼

table-cell 佈局

CSS

.box {
            width: 100%;
            min-height: 100vh;
            display: table;  //修改地方
        }

        .box>article {
            display: table-cell;  //修改地方
        }

        .box-left {
            width: 160px;
            min-height: 100vh;
            background: greenyellow;
        }

        .box-right {
            min-height: 100vh;
            background: darkcyan;
        }
複製代碼

grid 佈局

CSS

.box {
            width: 100%;
            min-height: 100vh;
            display: grid;  //修改地方
            grid-template-columns: 160px auto;   //修改地方
        }
        .box-left {
            background: greenyellow;
        }

        .box-right {
            background: darkcyan;
        }
複製代碼

後續:

最近完成 項目

若是有興趣想看下這項目話,帳號爲12345678911,密碼123或者本身註冊下帳號html

順便開源下這項目源代碼

相關文章
相關標籤/搜索