我想在屏幕中間設置3x3網格的方形單元格。每個單元應該包含一個令牌圖像(存儲在資產/圖像/...) .下面是重要的部分:如果我改變瀏覽器窗口的大小,令牌應該被調整大小,但不能被裁剪、拉伸或擠壓。所有9個令牌必須在屏幕上保持可見,并保持其形狀為正方形。
與此等價的是用背景圖片:background-image:URL(' assets/images/background . jpg ');背景-大小:包含;
scc網格有類似的功能嗎?
使用下面的代碼,我避免了單元格被拉伸或擠壓,當我水平擴展屏幕時,它們仍然被裁剪。
帶有二次瀏覽器窗口的網格 帶有矩形瀏覽器窗口的網格
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2%;
}
.square {
aspect-ratio: 1 / 1;
display: flex;
align-items: center;
padding: 5%;
background-color: #1E1E1E;
color: #fff;
}
.square img {
width: 100%;
height: 100%;
object-fit: contain;
object-position: center;
}
.square.fullImg {
padding: 0;
}
.square.fullImg img {
object-fit: cover;
}
<div class="grid">
<div class="square"><img src="https://picsum.photos/150" alt="Sorcerer"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Architect"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Warrior"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Healer"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Merchant"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Necromancer"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Alchemist"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Artisan"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Trickster"></div>
</div>
而不是為設置縱橫比。方形,用在。網格,并確保其高度不超過100vh:
.grid {
margin: 0 auto; /* This does the centering */
aspect-ratio: 1 / 1;
max-height: 100vh;
}
記得刪除& ltbody & gt的默認保證金,如果你還沒有這樣做:
body {
margin: 0;
}
試試看:
body {
margin: 0;
}
.grid {
margin: auto;
aspect-ratio: 1 / 1;
max-height: 100vh;
}
/* Original styles */
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2%;
}
.square {
display: flex;
align-items: center;
padding: 5%;
background-color: #1E1E1E;
color: #fff;
}
.square img {
width: 100%;
height: 100%;
object-fit: contain;
object-position: center;
}
<div class="grid">
<div class="square"><img src="https://picsum.photos/150" alt="Sorcerer"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Architect"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Warrior"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Healer"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Merchant"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Necromancer"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Alchemist"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Artisan"></div>
<div class="square"><img src="https://picsum.photos/150" alt="Trickster"></div>
</div>