首页 > 解决方案 > 如何使图像中的 div 居中?(使用 flex 但不使用 background-img)

问题描述

像往常一样,我拼命地用 css 尝试了几个小时;)如果还不够清楚,我很抱歉,我尽量让它尽可能容易理解。

我有一个模糊的图像,想在其中放置一个 div,并将其居中。最好的办法是让这两个元素彼此相邻

<parent/>
<child/>

因为父母是模糊的,而孩子不是。我试过这个

<parent class="blured">
    <child class="notblured"/>
</parent>

.blured{
    -moz-filter: blur(5px);
    -ms-filter: blur(5px);
    filter: blur(5px);
}

.notblured{
    -moz-filter: blur(0) !important;
    -ms-filter: blur(0) !important;
    filter: blur(0) !important;
}

child{
    margin: auto;
    width: 19em;
}
parent{
    display: flex;
    justify-content: center;
    align-items:center;
}

但这不起作用,两者都模糊了+我的图像不是我想要的样子

所以我希望它们彼此相邻,然后我可以手动将其居中,但它没有响应......

child{
    padding: 1.5em;
    text-align:center;
    width: 19em;
    padding-top:0.5em;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    top: 6em;
    left: 0;
    right: 0;
}

有什么建议吗?

标签: htmlcssflexbox

解决方案


将带有滤镜模糊的图像放在伪元素:before:after上,这样滤镜不会影响子元素。也需要一些z-index来使用这种确切的方法。

.parent {
  position: relative;
  display: flex;
  justify-content: center;
  align-items:center;
  min-height: 100vh;
}
.parent:before {
  content: '';
  position: absolute;
  height: 100%;
  width: 100%;
  background-image: url('https://picsum.photos/200/300');
  background-size: cover;
  -moz-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  z-index: 1;
}
.child {
  position: relative;
  color: white;
  background: green;
  min-height: 200px;
  min-width: 300px;
  z-index: 9;
}
<div class="parent blured">
    <div class="child">CHILD</div>
</div>


推荐阅读