John
John

Reputation: 131

Image need to resize by half based upon first div image

I have two different type of image with various sizes inside the two div tags. I need to resize the 2nd div image size by half of first div image.

.first-div img {
  width:500px; //this img size may be random
}
.second-div img {
  width:250px;//need to resize the img half of first-div image
}
<div class="first-div">
<img src="https://i.pinimg.com/originals/99/68/8e/99688e0cebdb1f8bde066b9bbf969003.jpg" width="" />
</div>

<div class="second-div">
<img src="https://cdn.pixabay.com/photo/2017/01/06/19/15/soap-bubble-1958650_960_720.jpg" width="" />
</div>

For example if the first div image size 200 and the second div image size 100. anyone help me to achieve this.

Upvotes: 0

Views: 99

Answers (3)

Gufran Hasan
Gufran Hasan

Reputation: 9373

You can achieve this by using jQuery like this:

 var img = new Image();

 img.onload = function() {
      alert(this.width + 'x' + this.height);
      var width = this.width;
      $('.second-div img').css('width',width/2);
 }
 var url = $('.first-div').find('img').attr("src"); // get dynamically url image
 img.src = url;

  or

 img.src = 'https://i.pinimg.com/originals/99/68/8e/99688e0cebdb1f8bde066b9bbf969003.jpg';//image_path_of_first_div_image;

Here you get width and height of image dynamically by passing image URL.

Upvotes: 1

Jtbs
Jtbs

Reputation: 301

With jQuery you can do

$('.second-div img').width($('.first-div img').width()/2)

Upvotes: 0

Athul Nath
Athul Nath

Reputation: 2606

By using Jquery

$('.second-div img').width($('.first-div img').width()/2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first-div">
	<img src="https://i.pinimg.com/originals/99/68/8e/99688e0cebdb1f8bde066b9bbf969003.jpg" width="" />
</div>

<div class="second-div">
	<img src="https://cdn.pixabay.com/photo/2017/01/06/19/15/soap-bubble-1958650_960_720.jpg" width="" />
</div>

You can achieve this by using css variables

:root {
    --main-width: 500px; 
}
img {
    vertical-align: middle;
    border-style: none;
}
.first-div img {
  width:var(--main-width); 
}
.second-div img {
  width:calc(var(--main-width)/2);
}
<div class="first-div">
	<img src="https://i.pinimg.com/originals/99/68/8e/99688e0cebdb1f8bde066b9bbf969003.jpg" width="" />
</div>

<div class="second-div">
	<img src="https://cdn.pixabay.com/photo/2017/01/06/19/15/soap-bubble-1958650_960_720.jpg" width="" />
</div>

Upvotes: 1

Related Questions