Select div 中的第一个元素
Select first element in div
当您不知道第一个元素是什么时,是否可以解决 div 中的第一个元素。
我有两个不同的 divs
<div class="templateOne">
<h1>Header 1</h1>
</div>
<div class="templateOne">
<h2>Header 2</h2>
</div>
然后我可以说
.templateOne > * {
margin-top: 0em;
}
或类似的东西。
.templateOne > *:first-child {
margin-top: 0em;
}
如果要使用第一个子元素的地址,可以使用:first-child
或:nth-child(1)
伪选择器。
.templateOne :first-child {
color: red;
}
<div class="templateOne">
<h1>Header 1</h1>
<p>Content 1</p>
</div>
<div class="templateOne">
<h2>Header 2</h2>
<p>Content 2</p>
</div>
如果您只想找到具有特定 class 名称的第一个元素,您可以使用 :first-of-type
或 nth-of-type(1)
:
.templateOne:first-of-type {
color: red;
}
<div class="templateOne">
<h1>Header 1</h1>
<p>Content 1</p>
</div>
<div class="templateOne">
<h2>Header 2</h2>
<p>Content 2</p>
</div>
当您不知道第一个元素是什么时,是否可以解决 div 中的第一个元素。
我有两个不同的 divs
<div class="templateOne">
<h1>Header 1</h1>
</div>
<div class="templateOne">
<h2>Header 2</h2>
</div>
然后我可以说
.templateOne > * {
margin-top: 0em;
}
或类似的东西。
.templateOne > *:first-child {
margin-top: 0em;
}
如果要使用第一个子元素的地址,可以使用:first-child
或:nth-child(1)
伪选择器。
.templateOne :first-child {
color: red;
}
<div class="templateOne">
<h1>Header 1</h1>
<p>Content 1</p>
</div>
<div class="templateOne">
<h2>Header 2</h2>
<p>Content 2</p>
</div>
如果您只想找到具有特定 class 名称的第一个元素,您可以使用 :first-of-type
或 nth-of-type(1)
:
.templateOne:first-of-type {
color: red;
}
<div class="templateOne">
<h1>Header 1</h1>
<p>Content 1</p>
</div>
<div class="templateOne">
<h2>Header 2</h2>
<p>Content 2</p>
</div>