0

I have two containers with text in them, and I'm trying to get their widths and add them together. I've set up a jsfiddle but it doesn't seem to work at all and I'm not sure why. I've used both width() and innerWidth().

this is the fiddle: http://jsfiddle.net/a83C6/

and this is the code:

HTML:

<div class="text-1">hello</div>
<div class="text-2">hello</div>

<div class="length"></div>

CSS:

.length {
  border:1px solid red;
  height:5px;
}

JS:

$(document).ready(function() { 
  $(".length").css({
    width:$(".text-1").innerWidth() + $(".text-2").innerWidth() 
  });
});
1
  • Seems to work fine. Each div is taking up the full length of the page. Times two and it's what you see. Commented Nov 27, 2013 at 20:00

1 Answer 1

1

div is a block level element so it takes the full width of the container, so adding them together of course will have the full width of both of them doubled up, If you want to take your div's take the actual width of its content alone, you can change it to inline-block or float it and calculate the width based on that.

Fiddle

You can do this without using JS as well, you can add a container

<div class="container">
    <div class="text-1 text">hello</div>
    <div class="text-2 text">hello</div>
    <div class="length"></div>
</div>

and

.container, .text {
    display:inline-block;
}

Fiddle

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

Comments

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.