Reputation: 95
I want to make image inside this div container not to affect its container size when stretching, I'd like it to go outside up and bottom if that's possible without setting container height or by assigning negative top or bottom with position.
.container {
display: flex;
background: skyblue;
height: 300px;
margin-top:50px;
}
img {
position:relative;
width: 500px;
top:-30px;
}
.column1 {
flex: 1;
}
.column2 {
flex: 1;
}
<div class="container">
<div class="column1">Hello world</div>
<div class="column2">
<img src="https://food.fnr.sndimg.com/content/dam/images/food/fullset/2013/6/28/0/FNK_Apple-Pie_s4x3.jpg.rend.hgtvcom.826.620.suffix/1382545039107.jpeg" alt="">
</div>
</div>
So basically what i want is for image to not affect container size, when stretching image size of the div to stays the same while it can go outside but without setting height for the div like this.
EDIT: I want to make image not affect it's div size ( that i can do with the height ) but i also want it to overlay not only from the bottom but also from the top of the div ( like it is now but without using negative top position in the css )
Upvotes: 2
Views: 2343
Reputation: 11
There is a very nice and cool way to make a background image work like an img element so it adjust its height automatically. You need to know the image width and height ratio. Set the height of the container to 0 and set the padding-top as percentage based upon the image ratio.
It will look like the following:
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: contain;
background-repeat: no-repeat;
width: 100 % ;
height: 0;
padding-top: 66.64 % ; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
Upvotes: 1
Reputation: 875
You can always set position: absolute;
on the image to bring it outside of the document flow which will have the effect you desire.
If you are not using flexbox another option will be to set float
which will bring the image outside of the document flow as well.
A third option will be to set height
to column2
to make it not care about children heights. But that's kind of a hack and I can't confirm it will work on all possible browsers.
.column2 {
height: 1px;
}
Also please keep in mind that by doing this the image will start to overlap elements that are below your container div.
Upvotes: 1