如何在::before伪元素中添加并缩放引号图标适配段落
问题描述
我想在段落开头添加引号图标,参考其他网站的实现效果,但调整width、height和font-size属性后,始终没法把图标缩放到适配段落的大小。
引号图标:
现有代码:
.article { padding-top: 2%; } .article::before { content: url(https://i.sstatic.net/mdeKRzYD.png); display: inline-block; /* top: 4px; */ /* float: left; */ /* width: 13px; */ font-size: 10px; }
<div class="article"> <p>Blah blah blah, some text to fill the space.</p> </div>
解决方法
核心问题是用content: url()引入图片时,直接设置width/height不会生效——这种方式引入的图片是替换元素,尺寸由图片本身决定。推荐用两种方案解决:
方案1:背景图片实现(更可控)
改用背景图片来承载图标,能灵活调整大小和对齐,同时给段落留出图标空间:
.article { padding-top: 2%; position: relative; padding-left: 2em; /* 给左侧图标预留空间 */ } .article::before { content: ''; display: inline-block; width: 1.2em; /* 用em单位适配文本字号 */ height: 1.2em; background-image: url(https://i.sstatic.net/zcvQGn5ns.png); background-size: cover; /* 让图片填满容器 */ position: absolute; left: 0; top: 0.2em; /* 调整垂直位置,和文本居中对齐 */ }
方案2:缩放content引入的图片
如果坚持用content: url(),可以通过transform: scale()来缩放,同时修正位置偏移:
.article::before { content: url(https://i.sstatic.net/zcvQGn5ns.png); display: inline-block; transform: scale(0.2); /* 按比例缩放,数值按需调整 */ transform-origin: left top; /* 从左上角开始缩放,避免图标偏移 */ margin-right: 0.5em; /* 给图标和文本之间留间距 */ }
内容的提问来源于stack exchange,提问作者user25017272
相关产品推荐
相关产品推荐

