css选择器可以插入图片吗

藏色散人
藏色散人 原创
2020-12-21 09:52:07 2614浏览

css选择器可以插入图片,如CSS选择器“:before”和“:after”,其插入方法就是使用content属性来插入图片,使用语法如“.p_beforeImg:before {content: ''; background...”}。

本教程操作环境:Windows7系统、HTML5&&CSS3版本,该方法适用于所有品牌电脑。

推荐:《css视频教程

CSS选择器:before、:after可以使用content属性来插入图片。

content 属性与 :before 及 :after 伪元素配合使用,在元素头或尾部来插入生成内容。

说明: 该属性用于定义元素之前或之后放置的生成内容。默认地,这往往是行内内容,不过该内容创建的盒子类型可以用属性 display 控制。

认识 :before 和 :after

默认 display: inline;

必须设置 content 属性,否则一切都是无用功, content 属性也只能应用在 :before 和 :after 伪元素上;

默认user-select: none,就是 :before 和 :after 的内容无法被用户选中;

伪元素可以和伪类结合使用形如:.target:hover:after。

:before 和 :after 是在CSS2中提出来的,所以兼容IE8;

::before 和 ::after 是CSS3中的写法,为了将伪类和伪元素区分开;

CSS 中其他的伪元素有:::before、::after、::first-letter、::first-line、::selection 等;

不可通过DOM使用,它只是纯粹的表象。在特殊情况下,从一个访问的角度来看,当前屏幕阅读不支持生成的内容。

示例1:通过before添加三角尖图片

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>css3</title>
    <style type="text/css">
        .p_beforeImg {
            background: #eeeeee;
            width: 200px;
            height: 80px;
            border-radius: 6px;
            padding: 10px 20px;
            position: relative;
        }
        .p_beforeImg:before {
            content: '';
            background: url('../img/triangle_up.png') no-repeat top left /32px 16px;/*兼容没测*/
            position: absolute;
            top: -15px;
            z-index: 2;
            width: 32px;
            height: 16px;
        }
    </style>
</head>
<body>
    <p class="p_beforeImg">通过before添加三角尖图片</p>
</body>
</html>

效果图:

9d9ef549cb604db04151ba1227d5857.png

示例2:

把before的地方换成after,插入图片样式用一下的就行

.p_afterImg {
        background: #eeeeee;
        width: 200px;
        height: 80px;
        border-radius: 6px;
        padding: 10px 20px;
        position: relative;
    }
    .p_afterImg:after {
        content: '';
        background: url('../img/triangle_down.png') no-repeat bottom right /32px 16px;/*兼容没测*/
        position: absolute;
        bottom: -15px;
        z-index: 2;
        width: 32px;
        height: 16px;
    }

效果图:

f7caede8aa46887e4eecacb7d9cba86.png

以上就是css选择器可以插入图片吗的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。