CSS单元素如何制作镜像效果

How to create mirrored image effect with CSS single element

我有一个带有背景图片的 HTML 元素,我想在底部创建一个镜像效果,就好像图像是这样反射的:

我创建此反射的最佳解决方案是 CSS 仅使用不超过此单个元素的元素并且不多次使用图像 URL(由于维护原因)。我只找到带有 "complicated" HTML 标记的 solutions like this

这是我的代码:

div {
  position: relative;
  background: url(https://i.stack.imgur.com/P56gr.jpg);
  width: 300px;
  height: 200px;
}
div:after {
  content: "";
  position: absolute;
  background: url(https://i.stack.imgur.com/P56gr.jpg);
  display: block;
  width: 300px;
  height: 200px;
  bottom: -210px;
}
<div></div>

你确实可以使用伪元素 :after:before 首先使用 transform: scaleY(-1); 镜像图像,然后用从半透明白色 rgba(255, 255, 255, 0.5) 到不透明白色 #fff.

为了不被强制标记图像 URL 两次,只需使用 background: inherit;.

div {
  position: relative;
  background: url(https://i.stack.imgur.com/P56gr.jpg) bottom;
  width: 300px;
  height: 200px;
}
div:after,
div:before {
  content: "";
  position: absolute;
  display: block;
  width: inherit;
  height: 50%;
  bottom: -52%;
}
div:after {
  background: inherit;
  transform: scaleY(-1);
}
div:before {
  z-index: 1;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0.5), #fff);
}
<div></div>

注意:您必须使用供应商前缀才能支持不同的浏览器。

只需添加

transform: rotate(180deg);
-webkit-mask-image:-webkit-gradient(linear, left 50%, left bottom, from(rgba(0,0,0,.7)), to(rgba(0,0,0,1)));

显然,在 css

中做这样的事情不会 100% 跨浏览器

div {
  position: relative;
  background: url(https://i.stack.imgur.com/P56gr.jpg);
  width: 300px;
  height: 200px;
}
div:after {
  content: "";
  position: absolute;
  background: url(https://i.stack.imgur.com/P56gr.jpg);
  display: block;
  width: 300px;
  height: 200px;
  bottom: -210px;
  transform: rotate(180deg);
  -webkit-mask-image:-webkit-gradient(linear, left 50%, left bottom, from(rgba(0,0,0,0)), to(rgba(0,0,0,.5)));
}
<div></div>