Martijn Ebbens
Martijn Ebbens

Reputation: 253

Center an overflowing image

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.

Upvotes: 3

Views: 162

Answers (5)

metahamza
metahamza

Reputation: 1455

Oh looks like I'm late to this party, but I was going to suggest this technique - using the ::after pseudo element to draw your square underlay and don't actually make the image overflow the wrapper div.

https://codepen.io/hamzatayeb/pen/QMxJvw

<div class="wrapper">
  <img class="image" src="http://pngimg.com/uploads/goat/goat_PNG13151.png">
</div>

Then this CSS -

.wrapper {
  width: 262px;
  height: 262px;
  position: relative;
  margin: 5em auto;
}

.wrapper::after {
  content: "";
  background: red;
  position: absolute;
  top: 16%; right: 16%; bottom: 16%; left: 16%;
  z-index: -1;
}

.image {
  padding-top: 25px;
  width: 100%;
  height: auto;
}

body {
  background: purple;
}

Upvotes: 0

Sikandar_ali
Sikandar_ali

Reputation: 174

Try this add this style only to your image

.image{
      width:175%;
      height:auto;
      position:absolute;
      top: -18px;
      right: -65px;
 }

JS Fiddle

Upvotes: -1

Jon Uleis
Jon Uleis

Reputation: 18639

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>

Upvotes: 4

A. W.
A. W.

Reputation: 671

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;
}

Upvotes: 1

Bitz
Bitz

Reputation: 1148

Try this:

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

It should center your <img> no matter the size of the parent div

Upvotes: 0

Related Questions