CSS中Grid布局中grid-template-columns与grid-template-row中auto的解释

背景

在复习Grid布局的时候.需要完成一个三列布局.其中两侧固定,中间自适应.

在这一过程中发现grid-template-columns中auto属性与预期不符.于是查阅了相关资料.

具体布局在下面代码中.

首先是MDN中关于auto的解释:如果该网格轨道为最大时,该属性等同于 <max-content> ,为最小时,则等同于 <min-content> 。

我对上句话的理解是auto属性值会在max-content与min-content之间取一个自适应值.但是实际上并不是如MDN解释的这样.

如果把下列代码复制到本地并预览,那么中间的class==center的元素会占满剩余空间.而并不符合max-content属性作用.(max-content : 栅格元素的大小是根据栅格元素中实际的内容的最大值而定.)

于是在网上查阅了一些关于auto属性值的说明 : The size of the rows is determined by the size of the container, and on the size of the content of the items in the row.

auto的值是根据外层容器的大小与栅格元素的内容共同决定的.而非只是在max-contnet于min-content之间取得一个自适应值.这点的描述上于MDN有一定的出入.也解释出为何设置为auto会占满剩余空间.

代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三列布局中间自适应</title>
    <style>
        .container {
            width: 100vw;
            height: 100vh;
            display: grid;
            grid-template-columns: 300px auto 300px;
            <!-- grid-template-columns: 300px max-content 300px; -->
            <!-- 以上两行代码产生的页面预期是不一致的. -->
        }
        .left {
            background: red;
        }
        .center {
            background: gold;
        }
        .right {
            background: green;
        }
        
    </style>
</head>

<body>
    <div class="container">
        <div class="left"></div>
        <div class="center">这是一个三列布局,中间自适应的布局</div>
        <div class="right"></div>
    </div>
</body>

</html>




参考

posted @ 2020-09-13 12:59  高坦的博客  阅读(2516)  评论(0编辑  收藏  举报