前端中伪元素的位置问题

本来想用元素的伪元素弄一个正六边形的,但是发现了一个问题,如图:
图片描述

1的位置是元素本体和before伪类的位置
2的位置是after伪类的位置。
代码如下:

<div class="hexagon"></div>
<style type="text/css">
.hexagon:before{
    width:100px;
    height: 173.2px;
    content: "";
    background-color: yellow;
/*    transform: rotate(-60deg);*/
    display: inline-block;
}
.hexagon {
    width: 100px;
    height: 173.2px;
    background-color: yellow;
    display: inline-block;
    margin:100px auto;
}
.hexagon:after{
    width:100px;
    height: 173.2px;
    content: "";
    background-color: yellow;
    /*transform: rotate(60deg);*/
    display: inline-block;
}


</style>

如果只有单一的伪类(after或before中的一个),在不设置position的情况下位置是重叠的(如图1).

阅读 13.3k
3 个回答

当然要在父元素中用position:relative,伪元素中用position:absolute了,要不然你怎么可能让它们之间叠加形成一个图形呀

<div class="hexagon"></div>
<style type="text/css">
.hexagon, .hexagon:before, .hexagon:after{
    width: 100px;
    height: 173.2px;
    background-color: yellow;
}
.hexagon {
    position: relative;
    margin: 100px auto;
}
.hexagon:before {
    position: absolute;
    content: "";
    transform: rotate(-60deg);
}
.hexagon:after {
    position: absolute;
    content: "";
    transform: rotate(60deg);
}
</style>

图片描述

试验了一下,把.hexagon的宽度设为200px,伪元素的宽度维持100px不变,结果.hexagon:after会并排在.hexagon:before左边,两个伪元素都覆盖在.hexagon之上。猜想:伪元素不在正常的文档流中,它们的位置不影响正常文档流中元素的位置,但伪元素和伪元素之间的位置会互相影响。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题