我想创建一个项目列表,并使用css网格来实现它。当前应该有四列,对于较大的屏幕,它会缩小到两列,而对于移动设备,只有一列。
一个基本的例子是
#techStack {
display: grid;
grid-template-columns: 25% 25% 25% 25%;
grid-gap: 20px;
}
.techStackItem {}
.techStackItemImg {}
.techStackItemTitle {
margin-left: 10px;
}
<div id="techStack">
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">this is the first item</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">number 2</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">nr. 3</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">the last item of this row</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">item nr. 5</span>
</div>
</div>
我想将这些项目水平居中。我将justify-items: center;
添加到了#techStack
,但结果看起来像这样:
我想将它们居中,但要减去它们的宽度以使它们从相同的X位置开始。不幸的是,它们的宽度未知,所以我无法做类似margin-left: 50%;
的操作并将其添加到图像中。
#techStack {
display: grid;
grid-template-columns: 25% 25% 25% 25%;
grid-gap: 5px;
background: black;
}
.techStackItem {
background: red;
}
.techStackItemImg {
margin-left: 50%;
}
.techStackItemTitle {
margin-left: 10px;
}
<div id="techStack">
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">this is the first item</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">number 2</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">nr. 3</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">the last item of this row</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">item nr. 5</span>
</div>
</div>
要解决该问题,我必须添加margin-left: calc(50% - x);
,但我不知道 x 。如何正确居中?假设每个元素的宽度为 70px ,那么最终结果将是
#techStack {
display: grid;
grid-template-columns: 25% 25% 25% 25%;
grid-gap: 5px;
background: black;
}
.techStackItem {
background: red;
}
.techStackItemImg {
margin-left: calc(50% - 70px);
}
.techStackItemTitle {
margin-left: 10px;
}
<div id="techStack">
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">this is the first item</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">number 2</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">nr. 3</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">the last item of this row</span>
</div>
<div class="techStackItem">
<img src="" class="techStackItemImg">
<span class="techStackItemTitle">item nr. 5</span>
</div>
</div>