How do I add negative margin equal to half the width of an image in css?

I am using an image from height: 100vh;

, so it resizes based on the screen resolution. I would like to add a negative left margin to it equal to half its width (which depends on the screen resolution). Any solution to do this with CSS only?

+3


source to share


1 answer


If the negative left position depends on (half) the width of the element, you can do this:

transform: translateX(-50%);

      

quick demo:



*{margin:0;}

img {
  vertical-align: top;
  height: 100vh;
  transform: translateX(-50%);
}
      

<img src="//placehold.it/800x600/0bf">
      

Run code


and hover animation



*{margin:0;}

.halfThere {
  vertical-align: top;
  height: 100vh;
  transition: 0.4s;
  transform: translateX(-50%);
}
.halfThere:hover {
  transform: translateX(0%);
}
      

<img class="halfThere" src="//placehold.it/800x600/0bf">
      

Run code


+1


source







All Articles