Valip
Valip

Reputation: 4610

Calculate width of element using jQuery

How can I set the width of an input equal with 100% - width of an img?

My goal is to display both of them on the same line and make the input to take the full width of the remaining space.

This is what I got so far

HTML:

<div class="img-container">
  <img src="http://dreamatico.com/data_images/car/car-1.jpg"/>
</div>
<input class="img-url" placeholder="enter img url" />

CSS:

.img-container {
  width: 30px;
  height: 30px;
}
.img-container img {
  width: 30px;
  height: 30px;
}

jQuery:

$(document).ready(function(){
  var img_container_width = $('.img-container').width();
  $(".img-url").width('100%' - img_container_width);
});

jsfiddle: https://jsfiddle.net/bko38bt2/2/

Upvotes: 1

Views: 2072

Answers (2)

adeneo
adeneo

Reputation: 318162

Logic dictates that 100% width means fill the entire parent, so basically the same width as the parent element

$(document).ready(function() {
    $(".img-url").width(function() {
        return $(this).parent().width() - $('.img-container').width()
    });
});

If you want to inline the elements easily, float them or add display: inline-block;

FIDDLE

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can do this with just css using Flexbox

.img-container {
  display: flex;
}
.img-container img {
  width: 30px;
  height: 30px;
}

input {
  flex: 1;
}
<div class="img-container">
  <img src="http://dreamatico.com/data_images/car/car-1.jpg"/>
  <input class="img-url" placeholder="enter img url" />
</div>

Upvotes: 2

Related Questions