roebeck
roebeck

Reputation:

Total width of a wrapping inline element

I want to find the total width of a SPAN which wraps around several lines. Is that possible? It's a single SPAN tag, with no other internal nodes...

If that's not possible, I would atleast like to find the left and right pixel offsets of the start and end of the SPAN.

Upvotes: 0

Views: 2027

Answers (4)

buti-oxa
buti-oxa

Reputation: 11431

You need to call getClientRects. You'll get an array of line rectangles and can add the width.

QuirksMode has a nice demo.

Upvotes: 1

rahul
rahul

Reputation: 187050

HI, I think you can achieve this by using getBoundingClientRect function.

var leftPosition = yourElement.getBoundingClientRect().left;
var rightPosition = yourElement.getBoundingClientRect().right;
var topPosition = yourElement.getBoundingClientRect().top;
var bottomPosition = yourElement.getBoundingClientRect().bottom;

I am not sure whether you are looking for this or not.

Upvotes: 1

Assembler
Assembler

Reputation: 794

you want to find the pixel width of a block of text if it was all one line?

I think what you might be able to do (and someone will downvote this for being wrong) is to use javascript to set up another span in another div off the page (e.g. style="top:-500px;"), take the 's innerHTML, drop it to the hidden span, take the width of the containing div, and then run with that.

I predict cross browser issues and heartache

<html>
<head>
<script>
function getSpanWidth(spanID){
    sourceSpan=document.getElementById(spanID)
    targetSpan=document.getElementById("spanmeasure")
    targetSpan.innerHTML=sourceSpan.innerHTML
    alert(targetSpan.offsetWidth+" "+sourceSpan.offsetWidth)
}
</script>
<style>
div{border:1px solid #cc0000;}
</style>
</head>

<body onLoad="getSpanWidth('spantext')">

<div style="width:100000px; top:-1000px;position:absolute;"><span id="spanmeasure"></span></div>
<div style="width:200px;">
<span id="spantext"> span text goes here, and then if there is lots and lots it will wrap around and be awesome! I'll put in more text to awesome it out even more... Awesome!
</span>
</div>
</body>
</html>

this seems to work on ie7 and ff. You will get variation if you don't use a reset style (because the default fonts are different)

also, if you set display:none, then the width will be 0.

Upvotes: 0

Ryan Florence
Ryan Florence

Reputation: 13483

var element = document.getElementById('someSpan');    
var elementWidth = element.offsetWidth;

No idea if that's what you're really asking, but that'll give you the width of the span.

Edit: After reading your question 3 more times I'm pretty sure this isn't what you're asking.

Upvotes: 0

Related Questions