need
The project needs to use v-for
instructions to render a list of images,
status quo
It was found that the last grid was not aligned with the green line below.
In the end, it was found that because each grid was given margin-right:36px
, it affected the last grid,
so use to remove the attribute last-child
of the last gridmargin
First of all, we have to understand what first-child and last-child are for:
first-child选择器用于选取属于其父元素的第一个子元素的指定选择器。
last-child选择器用于选取属于其父元素的最后一个子元素的指定选择器。
We need to pay attention :first-child伪类
to ensure that there are no sibling element nodes in front when using it, and :last-child
ensure that there are no sibling element nodes behind when using pseudo-classes.
Unmodified
<div v-for="(item, index) in exportData.slice(3, 8)" :key="index">
<div class="murightPart devicePart rectImg defaultrectImg">
<div class="deviceTitle">{
{ item.name.slice(0, 2) }}</div>
<div class="deviceTitle">{
{ item.name.slice(2, 5) }}</div>
</div>
</div>
</div>
CSS styles in the project
.muPart {
display: flex;
}
.murightPart {
margin-right: 36px;
}
.murightPart :last-child{
margin-right: 0px;
}
modified code
<div class="muPart">
<div v-for="(item, index) in exportData.slice(3, 8) "
:key="index"
class="murightPart">
<div class="devicePart rectImg greenRect">
<div class="deviceTitle">{
{ item.name.slice(0, 2) }}</div>
<div class="deviceTitle">{
{ item.name.slice(2, 5) }}</div>
</div>
</div>
</div>
css code
.muPart {
display: flex;
}
.murightPart {
margin-right: 36px;
}
.murightPart:last-child {
margin-right: 0px;
}
Because,
From the code in the figure,
murightPart
the style class is set last-child
. At the same time, we must know: last-child refers to the last child element under the parent element . To make the style under last-child effective, you need to ensure that the class is muPart
under The div tag has no sibling tags, or create a separate div tag to last-child
wrap the tags that need to take effect, and the first-child selector is the same.
从修改好的与未修改好
The modified HTML is just one tag under the class muPart
, and other elements are generated div
by relying on the div inside . In addition to the v-for tag, there is another sibling tag below, which renders the page Finally, the element under last-child is tagged to this brother, and the style of the last tag generated under all v-for does not take effect.v-for
未修改好的HTML
At the same time, you can also consider using first-of-type and last-of-type,
first-of-type
It matches the first one of this type. What does the type refer to? It is the thing matched before the colon. For example, p:first-of-type
it refers to the first one of all p elements. Here it is no longer limited to the first child element, as long as it is 该类型元素的第一个
, of course, the scope of these elements all belong to the same level, that is, the same generation.