伪元素为什么要设置绝对定位

Posted webcyh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了伪元素为什么要设置绝对定位相关的知识,希望对你有一定的参考价值。

效果实现了,但是没理解为什么要设置绝对定位,高手们谁知道?        /*使用伪元素制作导航列表项分隔线*/ .nav li:after     content:"";         width:1px;         height:20px;         position:absolute;/*为什么要设置绝对定位*/         top:15px;         right:0px;         background-image:linear-gradient(to top,#f00,#000);

 

绝对定位脱离文档流,且具有跟随性,即紧随在它之前的元素(未设置绝对定位的元素)的后面,且不占据任何空间。这个时候给他设置top, right 从而完美控制伪元素的位置,且不需要加入padding margin 以免影响整体宽高值。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
    p
        position: relative;
    
        span
            position: absolute;
        
        .test
            display: block;
            box-sizing: border-box;
            width:100px;
            height:100px;
            position: absolute;
            background:#3f3f3f;
            padding:20px 20px;
            color:white;
            bottom:300%;
            left:-50px;
            visibility: hidden;


        
        .test::after
            top:100%;
            content: " ";
            border-width:20px;
            border-style: solid;

            position: absolute;
            background:#3f3f3f;
            border-color: black white  white white;
            margin-left:50%;
            left:-20px;

        
        .a
            margin-left:40px;
            display: block;
            position: relative;
            margin-top:200px;
        
        .a:hover .test
            visibility: visible;
        
    </style>
</head>
<body>
<p>asdfasdf
<span>sdf</span></p>

<a href="" class="a">
    <div class="test">
    hello world!
</div>
sd
</a>


</body>
</html>

技术图片

 创建一个透明图像

以上是关于伪元素为什么要设置绝对定位的主要内容,如果未能解决你的问题,请参考以下文章

两个DIV,父元素相对定位没有设置高度,子元素绝对定位高度随内容变化,此无法撑开父DIV

css如何避免绝对定位覆盖其他元素?

绝对定位元素可以做css3 动画吗

子元素相对父元素绝对定位之后父元素没有高度怎么办

position absolute 绝对定位 设置问题

绝对定位