简体   繁体   English

如何在内联样式中添加nth-child()样式?

[英]How to add nth-child() style in inline styling?

How can I add a nth-child(n) declaration while applying inline styles to an element (which, obviously, contains multiple elements). 在将内联样式应用于元素(显然,包含多个元素)时,如何添加nth-child(n)声明。

For example, suppose I have a div that contains three p elements. 例如,假设我有一个包含三个p元素的div

The general stylesheet rules would go like this: 一般样式表规则如下:

div p:nth-child(2) {
  color: blue;
}

But how can I still colour the second paragraph blue while applying an inline style to the containing div ? 但是,在将内联样式应用于包含div如何将第二段颜色设置为蓝色?

An inline style attribute only pertains to the element with the attribute. 内联样式属性仅适用于具有该属性的元素。 So for example, if you have a style attribute on a div , the styles will only apply to that div (inherited properties and conflicting styles notwithstanding). 因此,例如,如果div上有style属性,则样式将仅应用于该div (尽管是继承的属性和冲突的样式)。 You cannot target a different element using an inline style attribute on another element. 您不能使用另一个元素上的内联样式属性来定位其他元素。

Even if you apply a style attribute onto a p element, you can't make the inline styles apply conditionally based on a pseudo-class. 即使将样式属性应用于p元素,也无法基于伪类有条件地应用内联样式。 See my answer to this question for why. 请参阅我对这个问题的回答。 However, if the markup is dynamically generated, you can control whether or not the style attribute gets printed in the first place using similar logic, but that is outside the scope of your question. 但是,如果标记是动态生成的,则可以使用类似的逻辑控制样式属性是否首先打印,但这超出了问题的范围。

Assuming the reason you want to apply the nth-child(n) declaration as an inline style is because you can't edit the CSS file or don't want to; 假设您想要将nth-child(n)声明应用为内联样式的原因是因为您无法编辑CSS文件或不想; but rather you need to apply your styling directly on the page, you could try just adding a <style> tag next to the div in question: 但您需要直接在页面上应用样式,您可以尝试在相关div旁边添加<style>标记:

<style>
  div.myContainer p:nth-child(2) {
    color: blue;
  }
</style>
<div class="myContainer">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>

I should note: this is not the ideal way to structure your code. 我应该注意:这不是构建代码的理想方法。 Styles and HTML/content should be separated to create properly formatted and semantic markup. 应分离样式和HTML /内容以创建格式正确和语义标记。

Also, if you have to apply this styling in more than one place, it can become messy and/or inconsistent. 此外,如果您必须在多个地方应用此样式,它可能会变得混乱和/或不一致。 However, I understand that sometimes you have to make exceptions depending on the project. 但是,据我所知,有时您必须根据项目制作例外。

li:nth-child(10n-2) {
    background: red;
}

This is the base for my source code! 这是我的源代码的基础!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM