gpt4 book ai didi

html - 我如何着手定位 div 的文字 "first-child",样式取决于元素类型

转载 作者:行者123 更新时间:2023-11-28 08:28:17 28 4
gpt4 key购买 nike

我正在为网站创建自定义 CSS,我遇到了将 CSS 应用于 div 的第一个子项的问题。我正在尝试仅对实际的第一个子元素使用特殊的 CSS 样式,具体取决于它的元素类型,并且该样式特定于该元素的类型。因此,仅当文章的第一个元素(在 div 中)是图像时,它才会忽略文章边距。如果文章的第一个元素是一个段落,它会创建一个额外的 margin-top。任何不是字面上的第一个(非 div)元素的东西都不应该应用任何第一个子元素规则。

我希望尽可能只使用 CSS,因为我只能将 CSS 应用于现有的 HTML。

这可能令人困惑。这jsfiddle使用与我的 html 非常相似的设置,并且我创建了一个 CSS 来显示我的错误。我知道我没有选择正确嵌套的 div,我只是不确定如何实现我想要的。在 fiddle 中,不同元素类型之后的每个元素都重新应用了第一个子规则。这又是因为我不确定要引用哪个 div。

这里又是我的代码:

HTML:

<article>
<div class="body entry-content">
<div class="sqs-layout sqs-grid-12 columns-12">
<div class="col sqs-col-12 span-12">

<div class="sqs-block image-block sqs-block-image">
<div class="sqs-block-content">
<div class="image-block-outer-wrapper">
<div class="intrinsic">
<div class="image-block-wrapper">
<img src="http://media.npr.org/images/picture-show-flickr-promo.jpg" alt="image"></img>


<div class="sqs-block markdown-block sqs-block-markdown">
<div class="sqs-block-content">
<p>p1</p>
<p>p2</p>
<p>p3</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

<div class="sqs-block markdown-block sqs-block-markdown">
<div class="sqs-block-content">
<p>p1</p>
<p>p2</p>
<p>p3</p>
</div>
</div>

<div class="sqs-block image-block sqs-block-image">
<div class="sqs-block-content">
<div class="image-block-outer-wrapper layout-caption-hidden">
<div class="intrinsic">
<div class="image-block-wrapper has-aspect-ratio">
<img src="http://media.npr.org/images/picture-show-flickr-promo.jpg" alt="image"></img>
</div>
</div>
</div>
</div>
</div>

<div class="sqs-block markdown-block sqs-block-markdown">
<div class="sqs-block-content">
<p>p1</p>
<p>p2</p>
<p>p3</p>
</div>
</div>

</div>
</div>
</div>

CSS:

    article {  
background-color:red;
padding:14px;
}
.body.entry-content {
padding:0px;
background-color:grey;
}
.body.entry-content p, img {
padding:0px;
margin:0px;
margin-bottom:1em;
}
.body.entry-content p:first-child{
/* Only the first paragraph in an article confines to red margine and creates an extra margin-top to space the content further from the title (not seen here). */
margin-top:1em;
background-color:blue;
}
.body.entry-content img:first-child {
/* Only the first image in an article ignores all red margins, filling the article.*/
margin:-14px -14px 0px -14px;
}

最佳答案

可能,但是所有那些嵌套的 div 使它变得非常丑陋:

.body.entry-content div:first-child div:first-child div:first-child .sqs-block-content > p:first-child{
background-color:blue;
}
.body.entry-content div:first-child div:first-child div:first-child .sqs-block-content div img:first-child {
margin:-14px -14px 0px -14px;
}

Fiddle here.

关于html - 我如何着手定位 div 的文字 "first-child",样式取决于元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420854/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com