html - 在 CSS 中设置伪元素尺寸
问题描述
我目前正在尝试设置 :before 伪元素宽度,以匹配元素本身的尺寸(在本例中为锚标记),目的是创建覆盖整个元素的叠加层。为了演示,对于这个示例,我将考虑使用 Google 的网页进行演示:
a.gb_g::before {
background-color: rgba(255, 0, 0, 0.2);
position: absolute;
content: 'hello';
display: block;
position: absolute;
}
<div class="gb_h gb_i">
<a class="gb_g" data-pid="23" href="https://mail.google.com/mail/?tab=wm&ogbl">Gmail</a>
</div>
但是,这会产生以下结果:
我也尝试过设置width: 100%
,但这会导致容器溢出。是否可以设置伪元素宽度,以完美匹配元素本身的宽度(在本例中为“Gmail”/“图像”链接)?期望的结果是覆盖完全覆盖每个锚标记,而不对元素本身进行任何 CSS 更改。
基本上,我面临的情况是我有一个固定的网页布局(现有样式我无法控制),为此我想突出显示网页的某些部分(包括一些链接)。因此,理想情况下,任何提议的解决方案都将对现有页面布局造成最小的影响,这就是我尝试选择完全基于伪元素的解决方案的原因。
解决方案
这对你有用吗?添加 position: relative to the element 和 width: 100% 到伪元素为我解决了这个问题。
a.gb_g::before {
background-color: rgba(255, 0, 0, 0.2);
position: absolute;
content: 'hello';
display: block;
position: absolute;
width: 100%;
}
a.gb_g{
position: relative;
}
<div class="gb_h gb_i">
<a class="gb_g" data-pid="23" href="https://mail.google.com/mail/?tab=wm&ogbl">Gmail</a>
</div>
推荐阅读
- foreach - 任何地方的自动化-对于文件夹循环命令中的每个文件在 223 个计数器后停止,它也会停止整个模块
- backoffice - 更新父订单时更新 ExtendedMultireferenceEditor(Hybris SAP Commerce 后台)
- python - 将响应发送回客户端时,AWS lambda 未完成执行
- ruby - 使用 Ruby 代码和 avro_turf gem 对消息进行编码失败,并出现“数据不是模式示例”错误
- svg - svg和g元素的区别?
- javascript - React Material Component 拒绝在代码沙箱中水平居中
- java - 无法为异步配置配置线程池任务执行器
- php - 如何根据另一个值更改使用哪个变量
- javascript - 在每个打印页面上打印带有标题的 FullCalendar
- database-design - 为 BI 的聚合导航设计事实表汇总的最佳实践