是否可以在 CSS 到 select 中专门没有 ID 或类的元素?

Is it possible in CSS to select an element specifically without an ID or class?

我正在为网站制作主题,但遇到了问题。我无法更改他们的 HTML 或使用 javascript,只能 CSS.

网站的 HTML 是这样的:

<div class="container">
  <div style="margin:a ridiculously massive number">
    <p id="title"> Title of page </p>
    <p> Words that cannot be read because of the ridiculous margin </p>
  </div>
  <div id="otherContent"> There a lot of divs without ridiculous margin all with different ids </div>
</div>

我想在不影响其他 div 边距的情况下删除荒谬的边距。这可能吗?

是的,您可以将 div 设为 .container 内部的 first-child,以免影响其他 div

.container div:first-child{
   //code
}

EXAMPLE 1

示例 1 专门针对您发布的示例,其中您想要定位的 div 是 parent 的第一个 child。另请注意,如果 margin 像您的示例一样内联,您将不得不 over-ride 它与 !important 像这样:

.container div:first-child{
   margin: 0 !important;
}

如果对方有类似的 class

,您也可以使用 :not 选择器
.container div:not(.classname) {
   //code
}

EXAMPLE 2

示例 2 的要点是,如果您的 div 不是第一个 child,并且是唯一没有 classclass(您可能不太可能有多个 divs 具有相同的 classname 除了一个但这是可能的)。在您的示例中,您还可以使用 :not() 来定位 ID 为 #otherContent 的其他 div,如下所示:

.container div:not(#otherContent) {
   //code
}

如果其他选项不适用,您可以使用的最后一个选项是 nth-of-type() 以具体定位您想要影响的选项:

.container div:nth-of-type(2) {
   //code
}

EXAMPLE 3

在这种情况下,您将不得不使用带有 !important 关键字的 first-child 选择器,因为这是使规则比 style="margin" 规则更具体的唯一方法:

.container > div:first-child {
    margin: 0 !important;
}

如果所有其他 div 都有 ID,您可以使用以下内容:

div>div:not([id]) {
    margin: 0 !important;
}