我正在尝试了解 CSS 网格的工作原理。我尝试制作一个商店商品的示例作为练习,但我不知所措。
这是我的 CSS 目前的样子。顶部被切断,间距奇怪,右侧根本没有连在一起。
理想情况下它是什么样的
这是我当前的CSS,我希望有人能帮助解释我在哪里误解了使用 CSS 网格。
.store-currency {
height: 3vh;
}
.item {
display: flex;
align-items: center;
grid-row: 1 / span 2;
}
.currency {
display: flex;
align-items: center;
}
#num-bought-item0 {
display: flex;
align-items: center;
justify-content: right;
margin-right: 10px;
grid-column: 1 / span 2;
}
.store-item {
height: 15vh;
width: 100%;
display: grid;
grid-template-columns: 2fr;
grid-template-rows: 1fr 1fr;
font-size: 24px;
color: white;
border: 5px white solid;
justify-content: left;
align-items: center;
}
.store-item img {
margin: 10px;
height: 8vh;
}
.store-container {
display: flex;
height: 100%;
width: 30vw;
z-index: 0;
background-color: saddlebrown;
left: 0;
position: absolute;
text-align: center;
}
HTML:
<div class="store-container">
<div class="store-item" id="item0">
<div class ="item">
<img src="dumbell.png" alt="">
<span>Dumbbell</span>
</div>
<div id="num-bought-item0">
<span>Owned</span>
<span id="count-item0">0</span>
</div>
<div class="currency">
<img class="store-currency" src="coin.png" alt="">
<span>100000</span>
</div>
</div>
最佳答案
您已经完成了第一步。
To get started you have to define a container element as a grid with display: grid, set the column and row sizes with grid-template-columns and grid-template-rows, and then place its child elements into the grid with grid-column and grid-row.
.store-container {
display: grid | inline-grid;
}
- grid – 生成 block 级网格
- inline-grid – 生成内联级网格
使用 grid-template-columns,您可以定义布局中显示的列数。 P.S Fr 单位是分数单位,1fr 表示可用空间的 1 部分。在此示例中,每列将占用大约 25% 的可用空间。
.container {
grid-template-columns: 1fr 1fr 1fr 1fr;
}
对于您的任务,您可以使用网格模板区域功能。
The grid-template-areas CSS property specifies named grid areas, establishing the cells in the grid and assigning them names.
例如:
.item-a {
grid-area: header;
}
.item-b {
grid-area: main;
}
.item-c {
grid-area: sidebar;
}
.item-d {
grid-area: footer;
}
.container {
display: grid;
grid-template-columns: 50px 50px 50px 50px;
grid-template-rows: auto;
grid-template-areas:
"header header header header"
"main main . sidebar"
"footer footer footer footer";
}
如果您需要更多示例,请查看此处: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-areas https://css-tricks.com/snippets/css/complete-guide-grid/ 一些示例取自第二个站点。
关于html - CSS 网格样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71536273/