如何将子元素的:before伪元素相对于父元素进行绝对定位?

10

这里是代码调试的链接.

我有两个div元素。

<div class="parent">
  <div class="child">
  </div>
</div> 

以及为此编写的CSS代码。

.parent {
  height: 20px;
  width: 100px;
  background-color: #080;
  position: relative;
}

.child {
  position: absolute;
  width: 80px;
  height: 200px;
  background-color: #008;
  right: -10px;
  top: 30px;
}

.child:before {
  border-right: 10px solid transparent;
  border-bottom: 10px solid #008;
  border-left: 10px solid transparent;
  top: -10px;
  width: 0;
  height: 0;
  content: "";
  position: absolute;
  left: 50%;
}
如何在不使用JS的情况下定位与父元素.parent相关的.child:before?我知道使用.parent:before可以解决问题,但对我来说并不好。

.child div的position属性值不是static时,这在CSS中是不可能实现的。不清楚你想做什么或为什么要这样做。 - Paulie_D
@Paulie_D 我正在尝试将.child:before相对于父元素居中。不能使用parent:before - cassln
是的...但为什么?.parent:before有什么问题吗?无论如何,正如我所说,这在CSS中不可能实现。 - Paulie_D
@Paulie_D 如您所见,蓝色三角形(.child:before)在语义上是.child的一部分。 - cassln
2个回答

6

我认为这就是你想做的。

我认为您会发现这更具有弹性和可扩展性。

.parent {
  height: 20px;
  width: 100px;
  background-color: #080;
  position: relative;
}
.child {
  position: absolute;
  width: 80px;
  height: 200px;
  background-color: #008;
  left: 50%;
  /* note 50% */
  top: 30px;
  margin-left: -20px;
  /* 2x your arrow size */
}
.child:before {
  position: absolute;
  border-right: 10px solid transparent;
  border-bottom: 10px solid #008;
  border-left: 10px solid transparent;
  top: -10px;
  /* your border size */
  margin-left: 10px;
  /* your border-size */
  width: 0;
  height: 0;
  content: "";
  left: 0;
}
<div class="parent">
  <div class="child">
  </div>
</div>


1
这是一个fiddle,看起来就是我需要的样子。但它使用了.parent:before,我希望能够使用.child:before来实现同样的效果。但也许这是不可能的。 - cassln
更新了...只是调整一下边距的问题。 - Paulie_D
正如我在兄弟答案中所说,这两个元素的宽度都可以是任意的。 - cassln
是的,但边距只与箭头宽度有关...其他所有内容都会根据元素的宽度对齐。- 看到了吗?- https://jsfiddle.net/5r0xzduh/ - Paulie_D
是的,现在我明白了,我的错误 :) 我认为这就是解决方案。 - cassln
请将子元素的顶部属性更改为30像素,请。这样可以防止重叠。 - cassln

4

你只能将一个元素 absolute 定位在最近的已定位父元素中。在这种情况下,是指 .child

如果你的布局中,.child.child:before 没有关系,为什么不将 .child:before 放置在父元素中,可以作为 .parent:before 或者它自己的元素呢?

或者,如果你的元素都有固定的宽度,就像你的例子一样,那么给伪元素一个固定的像素位置即可。演示链接


不,两个元素的宽度可以是任意的。是的,parent:before 可以工作。但是正如你所看到的,蓝色三角形(.child:before)在语义上是 .child 的一部分。 - cassln

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接