如何使用first-child/first-of-type仅设置博客首段为大字体?
如何仅让目标首段落应用大字体样式?
我希望博客文章的第一个段落显示为大字体,但尝试使用first-child和first-of-type选择器时,不仅影响了article下第一个div的首段,还影响了所有子div的首段。我仅想让class为sqs-layout的div内的第一个段落变大,却导致所有子div的首段都被影响。我尝试了多种写法,包括子选择器>、祖先选择器,相关代码如下:
尝试过的CSS代码
article.BlogItem > h1.BlogItem-title + div p:first-of-type { font-size: xx-large; } article.BlogItem > div p:first-of-type { font-size: xx-large; }
对应的HTML结构
<article id="post-64bb9b9f2da2562b9743df79" class="BlogItem"> <h1 class="BlogItem-title"></h1> <div class="sqs-layout"> <div class="row sqs-row"> <div class="col sqs-col-12 span-12"> <div class="sqs-block html-block sqs-block-html"> <div class="sqs-block-content"> <div class="sqs-html-content"> <p>First para should be big </p> <p>Second para should be small</p> </div> </div> </div> <div class="sqs-block html-block sqs-block-html"> <div class="sqs-block-content"> <div class="sqs-html-content"> <p>Second div First para, should be small </p> <p>Secondd div Second para, should be small</p> </div> </div> </div> </div> </div> </article>
解决方案
问题出在之前的选择器范围太广,p:first-of-type会匹配每个父容器下的第一个<p>标签,所以所有嵌套div里的首段都会被选中。想要仅定位到目标段落,需要精准锁定到.sqs-layout下的第一个内容块里的首段:
article.BlogItem > .sqs-layout .sqs-block:first-of-type .sqs-html-content p:first-of-type { font-size: xx-large; }
选择器说明:
article.BlogItem > .sqs-layout:直接选中article下的.sqs-layout容器,避免嵌套层级干扰.sqs-block:first-of-type:仅选中.sqs-layout下的第一个.sqs-block内容块.sqs-html-content p:first-of-type:选中该内容块内的第一个<p>标签
这样就能确保只有目标首段落被设置为大字体,后续内容块里的段落不会受到影响。
内容的提问来源于stack exchange,提问作者Ingeborg
相关产品推荐
相关产品推荐

