简体   繁体   中英

CSS - vertically center a div on a image

I have the following html:

  <div class='container'>
    <img src="http://lorempixel.com/400/400" />
    <div class='button-left'><</div>
  </div>

What I would like to achieve is for .button-left to always be in the center of the image, no matter the image size, but instead the div gets positioned according to my html element.

This is my css:

.container img {
  position: relative;
}
.button-left {
  position: absolute;
  top: 50%;
  background-color: red;
}

Shouldn't the .button-left div position according to the relative positioned image?

JsBin in case you want to try out a live demo: https://jsbin.com/cuwaguyiza/edit?html,css,output

You have to set position: relative to the container and not to the image. Also I suggest translating the button up, so it is perfectly centered.

.container {
    position: relative;
}

.button-left {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

Dont use position when no need it.

  1. Flexbox.

     .container { display: flex; align-items: center; } 
     <div class='container'> <img src="http://lorempixel.com/400/400"> <div class='button-left'>Lorem</div> </div> 

  2. Line-height (if u text is single-line)

 .container img { vertical-align: middle; } .button-left { display: inline-block; line-height: 400px; } 
 <div class='container'> <img src="http://lorempixel.com/400/400"><!-- dont delete this comment --><div class='button-left'>Lorem</div> </div> 

    .container img {
    position: relative;
}
.button-left {
    left: 50%;
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    background-color: red;

}

OR

.container img {
    position: relative;
    display: block;
    margin: 0 auto;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM