0

Let's say I have an image tag inside of a div, like so:

<div class="parent">
   <img class="child" src="url" alt="" />
</div>

I want the parent div to have a padding all all four sides that is equal to half the length of the image's height. So, if the image has a dimension of 200px by 50px, I want the parent's padding to be 25px on all four sides.

I want to do this so that it's responsive to changes in the image's size -- i.e. not hard coding the values.

Any way to do this? Thanks.

geenpill
  • 119
  • 8
  • use javascript to calculate the image height then apply your formula and pass the padding to parent div. Hope you understand – Zaid Bin Khalid Sep 09 '21 at 00:08
  • try https://stackoverflow.com/questions/384145/expanding-a-parent-div-to-the-height-of-its-children – Mulli Sep 09 '21 at 00:10

3 Answers3

0

You can use getBoundingClientRect to get the height of the element.

Calculate the padding with your formula and set it.

And add an eventListener to the window on resizing to update the padding

const img = document.querySelector('.child');
const parent = document.querySelector('.parent');

function setPadding() {
  parent.style.padding = `${img.getBoundingClientRect().height / 2}px`;
}

setPadding();
addEventListener('resize', setPadding);
a.mola
  • 3,883
  • 7
  • 23
0

Try like this it will give the perfect padding to the parent element.

const imgHeight  = document.querySelector(".child").naturalHeight;
const applyPadding  = (imgHeight/2);
$('.parent').css('padding',applyPadding);
body{
background-color:gray;
}
.parent{
background-color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
   <img class="child" src="https://learncodeweb.com/wp-content/uploads/2020/11/logo.png" alt="" />
</div>
Zaid Bin Khalid
  • 748
  • 8
  • 25
0

You apply the padding to the img instead and you make the parent an inline-block element. The reference of the percentage will be based on the parent dimension that is also based on the image dimension.

.parent {
  display:inline-block;
  border:1px solid;
}
.parent img {
  display:block;
  padding:10%; /* or margin:10% */
  width:80%;
}
<div class="parent">
   <img class="child" src="https://picsum.photos/id/1069/200/200" />
</div>

<div class="parent">
   <img class="child" src="https://picsum.photos/id/1069/100/100" />
</div>

<div class="parent">
   <img class="child" src="https://picsum.photos/id/1069/50/50" />
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415