Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center an overflowing image

Tags:

html

css

I'm trying to make an image that overflows on it its parent div, but that's centered according to its parent.

Heres how I'd like it to look:

enter image description here

This is the code I currently have but obviously doesn't work,

.wrapper{
  height:150px;
  width:150px;
  position:relative;
  background:red;
  margin:5em auto;
}

.image{
  width:175%;
  height:auto;
  position:absolute;
}

body{
  background:purple;
}
<div class="wrapper">
  <img class="image" src="https://pngimg.com/uploads/goat/goat_PNG13151.png">
</div>

JSFiddle
Fiddle

I want to achieve this in pure css, no use of javascript.

like image 922
Martijn Ebbens Avatar asked Dec 10 '25 03:12

Martijn Ebbens


2 Answers

You can center your image with the "negative translate" trick.

Here's a working example:

.wrapper {
  height: 150px;
  width: 150px;
  position: relative;
  background: red;
  margin: 5em auto;
}

.image {
  width: 175%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

body {
  background: purple;
}
<div class="wrapper">
  <img class="image" src="https://pngimg.com/uploads/goat/goat_PNG13151.png">
</div>
like image 165
Jon Uleis Avatar answered Dec 11 '25 21:12

Jon Uleis


Based on this question.

.wrapper{
  height:150px;
  width:150px;
  position:relative;
  background:red;
  margin:5em auto;
}

.image{
  width:175%;
  height:auto;
  position: absolute;
  top: -9999px;
  bottom: -9999px;
  left: -9999px;
  right: -9999px;
  margin: auto;
}

body{
  background:purple;
}
like image 38
A. W. Avatar answered Dec 11 '25 22:12

A. W.



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!