选择在CSS

时间:2015-07-03 14:00:22

标签: html css html5 css3 css-selectors

如何使用预定义的类margin-bottom: 20px;覆盖框架设置的.alert,并在元素后跟另一个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>

我知道相邻选择器可以通过仅选择紧跟在另一个.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会撤消先前margin-bottom: 20px;的{​​{1}},但是有一种方法可以直接选择.alert,如果它来到另一个.alert之前覆盖它{ {1}}到.alert

2 个答案:

答案 0 :(得分:3)

如果我理解正确,你想要

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

&#13;
&#13;
@import 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css';
.alert {
  margin-bottom: 0;
}
.alert:last-child {
  margin-bottom: 20px;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您要求的是previous sibling&#39;通过它的声音选择器是不可能的。

CSS只能选择一个元素(如果它是一个子元素)或adjacently成功的元素。您无法在CSS中选择相邻的前一个元素(或父元素)。

您的解决方案完全可以接受。负利润率有时被视为“肮脏的”&#39;出于某种原因但这远非真实,而且正式documented

  

允许保证金属性的负值,但可能存在   特定于实施的限制。

您的解决方案是正确的!