首页 > 解决方案 > 使用 Flexbox/Grid 模糊 CSS 中以容器为中心的图像背景

问题描述

我难住了。我想创建这样的东西:在此处输入图像描述

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

我有这样的事情:

<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。如何为此添加背景模糊并将图像居中放置在容器中?我正在考虑将背景图像添加到容器中,但如果我在其上添加模糊,整个容器就会变得模糊。

标签: cssflexboxgrid

解决方案


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

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>


推荐阅读