如何使元素定位在右边:0,如果它已经离开:0样式在其中一个类

时间:2016-07-15 10:37:20

标签: css

我有一个带有A类的元素,带有规则:

.A {
    left: 0px;
}

出于某种原因,我需要将元素放在容器内的正确位置,我不能排除A类。

1 个答案:

答案 0 :(得分:2)

特殊性是您的朋友:

这里有几个选项......

使用其他特异性覆盖该类,例如另一个类(或ID)

.container {
  height: 50vh;
  position: relative;
  width: 50%;
  bordeR: 1px solid grey;
  margin: auto;
}
.A {
  position: absolute;
  height: 25px;
  width: 25px;
  left: 0;
  background: #000;
  margin-bottom: 1em;
}
.A.right {
  left: auto;
  right: 0;
  background: red;
}
<div class="container">
  <div class="A"></div>
  <div class="A right"></div>
</div>

nth-child选择

.container {
  height: 50vh;
  position: relative;
  width: 50%;
  bordeR: 1px solid grey;
  margin: auto;
}
.A {
  position: absolute;
  height: 25px;
  width: 25px;
  left: 0;
  background: #000;
  margin-bottom: 1em;
}
.A:nth-child(2) {
  left: auto;
  right: 0;
  background: red;
}
<div class="container">
  <div class="A"></div>
  <div class="A"></div>
</div>