繁体   English   中英

取消设置多个 CSS 背景图像之一时使用 URL 进行 DRY

[英]DRY with URLs when unsetting one of multiple CSS background-images

我使用多个背景图像。 在某些规则下,我希望其中一个不要出现。

当然,我不想重复上级规则(即图像 URL)。 我想将其中一个设置为none ,同时让其他人保持原样(即继承自不太具体的规则)。

不幸的是,类似于background-image: none, initial|auto|unset|inherit; 不起作用,因为这些关键字都有其他用途或目标。

有没有办法定位特定的 CSV 项目? 有合适的关键词吗? 或者现在和将来的 CSS 没有办法避免重复吗?

 div{ background-image: url(https://placekitten.com/200/300), url(https://placekitten.com/200/300); } div:hover{ background-image: none, /*DRY→*/ url(https://placekitten.com/200/300) /*←DRY*/; }
 <div style="width:400px;height:300px;background-position:left -2em,right 2em;background-repeat:no-repeat;"></div>

CSS 变量可以在这里提供帮助

 div { --img:url(https://placekitten.com/200/300); background-image: var(--img), var(--img); } div:hover { background-image: none, var(--img); }
 <div style="width:400px;height:300px;background-position:left -2em,right 2em;background-repeat:no-repeat;"></div>

或者使用伪元素继承:

 .box { width: 400px; height: 300px; background-position: right 2em; background-repeat: no-repeat; background-image: url(https://placekitten.com/200/300); position: relative; z-index: 0; } .box::before { content: ""; position: absolute; z-index: -1; top: 0; left: 0; right: 0; bottom:0; background:inherit; background-position: left -2em; } .box:hover::before { content:none; }
 <div class="box"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM