美文网首页
CSS网格布局学习(1)

CSS网格布局学习(1)

作者: 贪恋冬天的幸福 | 来源:发表于2020-07-21 11:43 被阅读0次

    CSS 网格布局,元素按自动定位规则布局:

    <!DOCTYPE HTML>
    <html>
    
    <head>
        <meta charset="utf-8">
        <style>
            .wrapper {
                display: grid;
                grid-template-columns: repeat(4, 1fr);
                grid-auto-rows: 200px;
                grid-gap: 20px;
            }
    
            .box1 {
                background-color: chartreuse;
            }
    
            .box2 {
                background-color: coral;
            }
    
            .box3 {
                background-color: cornflowerblue;
            }
    
            .box4 {
                background-color: darkblue;
            }
        </style>
    </head>
    
    <body>
        <div class="wrapper">
            <div class="box1">One</div>
            <div class="box2">Two</div>
            <div class="box3">
                This block is absolutely positioned. In this example the grid container is the containing block and so the
                absolute positioning offset values are calculated in from the outer edges of the area it has been placed
                into.
            </div>
            <div class="box4">Four</div>
        </div>
    </body>
    
    </html>
    

    布局如下:


    grid 布局

    如果定位了其中一个元素,则这个元素按指定单元格放置,剩余元素仍按照自动定位规则布局:

    .box3 {
                grid-column-start: 2;
                grid-column-end: 4;
                grid-row-start: 1;
                grid-row-end: 3;
                background-color: cornflowerblue;
            }
    

    布局如下:


    grid 布局

    如果其中一个元素,使用了绝对定位,如果增加 wrapper 元素的 position 为 relative,则会相对与当前网格进行定位:

    .wrapper {
        position: relative;
    }
    

    修改 box3 的 position 属性为 absolute,并且设置 top 和 left 属性:

    .box3 {
        position: absolute;
        top: 40px;
        left: 40px;
    }
    

    box3 元素变成了绝对定位:

    定位上下文为当前网格

    如果不为 wrapper 元素添加 position: relative, 则定位上下文就变成了当前视口(该项目不再被视为网格布局的一部分,当网格中其他元素调整尺寸或自动布局时,都与该项目无关):

    定位上下文为当前视口

    相关文章

      网友评论

          本文标题:CSS网格布局学习(1)

          本文链接:https://www.haomeiwen.com/subject/zycikktx.html