Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background image shrinking but not div

Tags:

html

css

flexbox

I'm new and am completely stumped by something. I have div with a background image. When the window is resized, the background image shrinks in height once the window is adjusted smaller than the width of the actual photo. I like the way this looks, but the div container is remaining the same height. Any text I have is not remaining vertically centered to the background picture (which is changing height), it is remaining centered to the div (which is not), so the text is floating off the image. Is there a way to make the container shrink in the same way that the background image is so everything stays centered?

#mainpic {
  margin: 0;
  width: 100%;
  height: 400px;
  background-image: url("http://www.aclefproductions.com/Images/pianoedit6.jpg");
  background-size: 100%;
  background-repeat: no-repeat;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div id="mainpic">
  <h3>Hello</h3>
</div>
like image 529
Jonathan Foster Avatar asked Mar 01 '26 01:03

Jonathan Foster


1 Answers

<div id = "mainpic">
  <h3>Hello</h3>
  <img src="http://www.aclefproductions.com/Images/pianoedit6.jpg">
</div>

 #mainpic {
  margin: 0;
  position: relative;
  }

  #mainpic img{
    width: 100%;
  }


  #mainpic h3{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); /*To account for the width and hight of the h3*/
    margin: 0;
  }

https://jsfiddle.net/4p3gek5x/

Enjoy

like image 94
Joonas89 Avatar answered Mar 03 '26 14:03

Joonas89



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!