Select 位于 CSS 中具有相同 class 的另一个元素之前的元素

Select an element that comes before another element with the same class in CSS

如何使用预定义的 class .alert 覆盖框架设置的 margin-bottom: 20px; 并在元素后跟另一个元素时将其设置回 0 .alert 元素。

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
  
  <div class="alert alert-success" role="alert">The <code>margin-bottom: 20px;</code> was set by the framework.</div>
  <div class="alert alert-info" role="alert">The <code>margin-bottom: 20px;</code> was set by the framework.</div>
  <div class="alert alert-warning" role="alert">The <code>margin-bottom: 20px;</code> was set by the framework.</div>
  
</body>

我知道相邻的 selector 可以通过 select 仅紧跟在另一个 .alert 元素之前的 .alert 元素来做一个技巧并设置它是 margin-top-20px 但这听起来很脏。

.alert + .alert {
  margin-top: -20px;
}
<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
  
  <div class="alert alert-success" role="alert">The <code>margin-bottom: 20px;</code> was retracted by the followed <code>margin-top: -20px;</code>.</div>
  <div class="alert alert-info" role="alert">The <code>margin-bottom: 20px;</code> was retracted by the followed <code>margin-top: -20px;</code>.</div>
  <div class="alert alert-warning" role="alert">The <code>margin-bottom: 20px;</code> was not retracted because there's no followed <code>.alert</code> element.</div>
  
</body>

CSS 会收回前面的 .alertmargin-bottom: 20px;,但是有没有办法直接 select 如果前面有 .alert另一个 .alert 将其 margin-bottom 覆盖为 0?

如果我没理解错的话,你想要

.alert {
  margin-bottom: 0;
}
.alert:last-child {
  margin-bottom: 20px;
}

@import 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css';
.alert {
  margin-bottom: 0;
}
.alert:last-child {
  margin-bottom: 20px;
}
<div class="alert alert-success" role="alert">The <code>margin-bottom: 20px</code> was overriden by <code>margin-bottom: 0</code>.</div>
<div class="alert alert-info" role="alert">The <code>margin-bottom: 20px</code> was overriden by <code>margin-bottom: 0</code>.</div>
<div class="alert alert-warning" role="alert">The <code>margin-bottom: 20px</code> was overriden by <code>margin-bottom: 20px</code>.</div>

您要求的是“previous sibling”select或通过它的声音,这是不可能的。

CSS 只能 select 一个元素,如果它是一个子元素或 adjacently 继承它。您不能 select CSS.

中相邻的前一个元素(或父元素)

您的解决方案完全可以接受。出于某种原因,负边距有时被视为 'dirty',但事实并非如此,官方说法是 documented

Negative values for margin properties are allowed, but there may be implementation-specific limits.

您的解决方案是正确的!