Code Tree
Code Tree

Reputation: 2209

make an element centered to an image on resizing using css

I have to make a div follow an image and sit on its center vertically and horizontally when responsive. I simply have no idea or don't think whether it is possible only by css. Any help is appreciated

enter image description here

Upvotes: 0

Views: 56

Answers (2)

.imageWrapper {
  height:200px;
  width:200px;
  position:relative;
  margin:50px auto 0px auto;
}

.imageWrapper > div:first-child {
  position:absolute;
  z-index:1;
  top:0px;
  left:0px;
  right:0px;
  bottom:0px;
  overflow:hidden;
}

.imageWrapper > div:first-child img{
  height:200px;
  width:100%;
  object-fit:cover;
  position:relative
}

.imageWrapper > div:last-child {
  position:relative;
  z-index:2;
  text-align:center;
  line-height:200px;
  height:200px; 
  width:100%;
}
<div class="imageWrapper">
  <div><img src="https://upload.wikimedia.org/wikipedia/commons/e/ee/Billede_084.jpg"></div>
  <div><p>bla bla</p></div>
</div>

make a wrapping div, make the image absolute as a background and place the text in front of the image.

Upvotes: 2

Yoarthur
Yoarthur

Reputation: 917

Well you can make good use of an old trick to center element using position property.

as usual an example is better than an explanation.

.html

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

.css

.parent {
  position: relative;
  width: 100%;
  height: 200px;
  background-color: lightblue;
}

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

Upvotes: 0

Related Questions