代码之家  ›  专栏  ›  技术社区  ›  lost9123193

使用Flexbox/Grid模糊CSS中以容器为中心的图像背景

  •  0
  • lost9123193  · 技术社区  · 5 年前

    我被难住了。我想创建这样的东西: 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,所以它也会考虑图像bg。我该如何添加背景模糊并将图像居中显示在容器中?我在考虑将backgground图像添加到容器中,但如果我在上面添加模糊,整个容器都会变得模糊。

    1 回复  |  直到 5 年前
        1
  •  0
  •   Akhil Aravind    5 年前

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

    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>
    推荐文章