背景
在復習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>