Maxiss
Maxiss

Reputation: 1056

How to center a div inside an image? (using flex but not background-img)

As usual I am desesperately trying everything with css for hours ;) if it's not clear enough I am sorry, I try to make it as understandable as posisble.

I have a blured image and would like to put a div inside it, and center it. the best would be to have the two elements next to each other

<parent/>
<child/>

because the parent is blured and the child isn't. I tried this

<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;
}

But this doesn't work, both are blured + my image isn't really the way I want it

So I would prefer to have them next to each others and then I can just center it manually, but it's not responsive then...

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;
}

Any suggestion?

Upvotes: 0

Views: 62

Answers (2)

BugsArePeopleToo
BugsArePeopleToo

Reputation: 2996

Put the image with the filter blur on a pseudo element :before or :after, that way the filter does not affect the child elements. Needs some z-index too to work with this exact approach.

.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>

Upvotes: 2

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

Use an outer element as parent for both, and center the child with the following CSS:

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

.outer{
  position: relative;
  width: 500px;
  height: 300px;
}

.child {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 150px;
  height: 100px;
  background: blue;
  transform: translate(-50%, -50%);
}

.parent {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  background: red;
}
<div class="outer">
  <div class="parent blured">
  </div>

  <div class="child">
  </div>
</div>

Upvotes: 1

Related Questions