How can I address the literal & ldquo; First-child & rdquo; From a div, sty…

I’m creating custom CSS for a website and I’m coming across an issue regarding applying CSS to first-child of div. I’m trying to have special CSS style the actual first child only, depending on the element type it is, and the style is specific to that element’s type. So, only if the article’s very first element (within an div) is an image, then it ignores article margins. If the article’s very first element is a paragraph, it creates an additional margin-top. Any thing that is not a literally first (non-div) element should not have any first-child rules applied.

I would like to do this by only using CSS if possible as I can only apply CSS to the existing HTML.

This is probably confusing. This jsfiddle
uses a very similar setup to my html, and I’ve created a CSS that shows my error. I understand I’m not selecting the correctly nested div, I’m just not sure how to achieve what I want. In the fiddle, every element after a different element type has a first-child rules re-applied. Which again is due to me being unsure which div to reference.

Here’s my code again:

HTML:

image

p1

p2

p3

p1

p2

p3

image

p1

p2

p3

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;
}

Possible, but all those nested divs make it really ugly :

.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.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » How can I address the literal & ldquo; First-child & rdquo; From a div, sty…

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录