Reputation: 2390
I have a fixed width container (div) and an image inside, this image should fit the container width but having a margin, like this:
I tried adding a padding to container, it makes container bigger.
My second attempt was adding a margin to the image, but it makes it go outside the container.
Both attempts are in this snippet:
$('.result1').html('div is ' + $('.test1').width() + ' and image is ' + $('.test1 img').width());
$('.result2').html('div is ' + $('.test2').width() + ' and image is ' + $('.test2 img').width());
div{
width: 300px;
background-color: #999;
}
img{
background-color: #FFF;
width: 100%;
}
.test1{
padding:10px;
}
.test2 img{
margin:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test1'>
<img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' />
</div>
<div class='result1'></div>
<div class='test2'>
<img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' />
</div>
<div class='result2'></div>
Upvotes: 0
Views: 1124
Reputation: 3584
I hope I understood your problem. You need to remove the margin you added to the image first. Than give padding to your div container and also add box-sizing: border-box to it-
$('.result1').html('div is ' + $('.test1').width() + ' and image is ' + $('.test1 img').width());
div{
width: 300px;
background-color: #999;
box-sizing: border-box;
padding: 10px;
}
img{
background-color: #FFF;
width: 100%;
}
.test1{
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test1'>
<img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' />
</div>
<div class='result1'></div>
<div class='test2'>
<img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' />
</div>
<div class='result2'></div>
Let me know if it works
Upvotes: 2
Reputation: 3461
You need to assign box-sizing: border-box;
to your container and then use your padding solution. This CSS stops padding from adding to the size of an element.
Upvotes: 1