我想将文本作为.contactSection下的第一个h1生效。但是我将nth-child(1)用于该类,.contactSection中的两个h1元素都受到处理。我不知道如何在第一个h1元素上添加一些边距。
.contactSection {
width: 100%;
text-align: center;
}
.contactSection button {
padding: 4% 16%;
background: #f42988;
border-radius: 30px;
color: cornsilk;
font-size: 10pt;
border: none;
}
.contactSection p {
padding: 0 2%;
z-index: 1;
position: relative;
}
.contactSection h1:nth-child(1) {
margin-top: 15px;
}
.formTitle {
font-size: 32px;
color: cornsilk;
}
.contactForm {
width: 80%;
background: #e32b7a;
margin: 5% 10%;
padding: 4% 10px;
border-radius: 30px;
}
<section class="contactSection">
<h1>Information</h1>
<div class="contactForm">
<div class="post">
<h1><span class="formTitle">This page is under construction</span></h1>
<p>This page will come up very soon. Sorry for inconvenience. We also post any info on facebook, Twitter, and Instagram. If you check out and follow them up, I would be greatful. Thanks!</p>
</div>
</div>
</section>
[如果您尝试在<h1 />
中获取第一个.contactSection
,最好的选择是使用child combinator:
.contactSection > h1 {
margin-top: 15px;
}
这将选择<h1 />
的第一个直接后代.contactSection
元素。如果在这种情况下,如果您只希望显示为.contactSection
div的first child的first h1,则可以将前者与:first-child
组合:
.contactSection > h1:first-child {
margin-top: 15p;x
}
.contactSection {
width: 100%;
text-align: center;
}
.contactSection button {
padding: 4% 16%;
background: #f42988;
border-radius: 30px;
color: cornsilk;
font-size: 10pt;
border: none;
}
.contactSection p {
padding: 0 2%;
z-index: 1;
position: relative;
}
.contactSection > h1:first-child {
margin-top: 15px;
}
.formTitle {
font-size: 32px;
color: cornsilk;
}
.contactForm {
width: 80%;
background: #e32b7a;
margin: 5% 10%;
padding: 4% 10px;
border-radius: 30px;
}
<section class="contactSection">
<h1>Information</h1>
<div class="contactForm">
<div class="post">
<h1><span class="formTitle">This page is under construction</span></h1>
<p>This page will come up very soon. Sorry for inconvenience. We also post any info on facebook, Twitter, and Instagram. If you check out and follow them up, I would be greatful. Thanks!</p>
</div>
</div>
</section>
答案:如果从嵌套元素中提及单个元素,则应在CSS中以>
大于符号来提及。
您的CSS这类代码:
.contactSection {
width: 100%;
text-align: center;
}
.contactSection p {
padding: 0 2%;
z-index: 1;
position: relative;
}
<!-- .contactSection h1:nth-child(1) {
margin-top: 15px;
This is not right way, please skip.
} -->
.contactSection > h1 {
color: red;
font-size: 30px;
}
.formTitle {
font-size: 30px;
color: green;
}
<section class="contactSection">
<h1>Information</h1>
<div class="contactForm">
<div class="post">
<h1><span class="formTitle">This page is under construction</span></h1>
<p>This page will come up very soon. Sorry for inconvenience. We also post any info on facebook, Twitter, and Instagram. If you check out and follow them up, I would be greatful. Thanks!</p>
</div>
</div>
</section>