1

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/

2
  • Do you want to display img and input inline? Commented Jan 25, 2016 at 11:27
  • Yes, I've update the question Commented Jan 25, 2016 at 11:28

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

This works, but the problem is that the .img-container has initially display:none; because it appears only after the input has an url...
Moved the display: none; to the img and now everything is ok. Thanks!
Great, glad i could help.
1

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

1 Comment

This doesn't works, I need the input to take all blank space that remains after the image because I'm also using this for mobile devices

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.