使用Flexbox / Grid来模糊CSS容器中居中图像的背景

问题描述 投票:0回答:1

我很困惑。我想创建类似这样的内容:enter image description here

背景为相同图像但模糊。限制是图像必须在容器中居中]

我有这样的东西:

<div className="image-container">
  <img className="image-to-show" url>
  <div className="image-bg"/>
</div>

我的问题是,要显示的图像必须在中间对齐。我有

.image-container{
 display:flex,
 align:center
}

img.image-to-show{
 width:60%
}

问题是,由于图像容器具有3个div,因此我无法将图像显示与中心对齐,因此它也将考虑image-bg。如何添加背景模糊并将图像居中放置在容器中?我当时正在考虑将背景图像添加到容器中,但是如果在其上添加模糊效果,则整个容器都会变得模糊。

css flexbox grid
1个回答
0
投票

这很容易实现,请看一下代码片段。为了获得清晰的结果,请在运行代码段后单击整页。

body, html {
  height: 100%;
  margin: 0;
}

.bg-image {
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTbDSiyg7FTcSl0C5Y1SNyXtIn6y5QZ_eUbvbmTwXeWJ2dXXl2ZiA&s");
  
  filter: blur(8px);
  -webkit-filter: blur(8px);
  
  /* Full height */
  height: 100%; 
  
  /* Center and scale the image nicely */
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

/* Position text in the middle of the page/image */
.bg-text {
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTbDSiyg7FTcSl0C5Y1SNyXtIn6y5QZ_eUbvbmTwXeWJ2dXXl2ZiA&s");
  background-repeat: no-repeat;
  background-size: 500px 300px;
  color: red;
  font-weight: bold;
  border: 3px solid #f1f1f1;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
  width: 80%;
  padding: 20px;
  text-align: center;
}
<div class="bg-image"></div>

<div class="bg-text">
  <h2>Blurred Background</h2>
  <h1 style="font-size:50px">I am John Doe</h1>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.