CyberJunkie
CyberJunkie

Reputation: 22674

Jquery get width of paragraph inside fixed width

I'm trying to find out the real width of a paragraph inside a container with a fixed width. I added float:left to the paragraph thinking this will work but it returns the width of the container width.

Updated

CSS

.outer {
    max-width: 320px;
    background: #fff;    
    display: inline-block;  
    box-sizing: border-box;
}
.inner span {      
    float: left;
    background: #ccc;
}

HTML

<div class="outer">
    <div class="inner"> 
        <span>
            <p>Vivamus suscipit tortor eget felis porttitor volutpat</p>  
        </span>
    </div>
</div> 

JQUERY

I want to alter the width of .outer based on the real width of the paragraph but I can't find out the real width. I'm using $('.inner span').innerWidth()) to output the width.

JSFIDDLE

http://jsfiddle.net/f2br8ppw/9/

In my example the width of longest line in the paragraph "Vivamus suscipit torto" is visibly smaller than 320px. How can I get the real width of the paragraph? (where the longest line of the paragraph ends is where the width should end - the white background should end at the word "torto")

The goal: Perfectly center text that is aligned left. I added a background white in the jsfiddle for a visual guide. Without the background the text doesn't look perfectly centered because there is an obvious space to the right of the paragraph.

Upvotes: 2

Views: 888

Answers (2)

Ian Clark
Ian Clark

Reputation: 9347

Short of using JavaScript, I can't think of a way of achieving this. That said, it's rather simple once you do.

We need to set the display of the paragraph to inline, which will take it's exact width rather than inline-block or using a float which will wrap to the container's width once the content spills onto multiple lines.

All we need to do then is to simply calculate the width of the paragraph and the container on load, and space appropriately. See Fiddle:

var $container = $(".outer"),
    $paragraph = $("p", $container);

$container.css("padding-left", ($container.width() - $paragraph.width()) / 2);
p {
    font-size: 30px;
    background-color: #ccc;
    display: inline;
}

.outer {
    width: 320px;
    background-color: #ddd;
    box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
  <p>Vivamus suscipit torto eget felis porttitor volutpat</p>  
</div> 

Upvotes: 1

dfsq
dfsq

Reputation: 193261

The output is correct: the width of the paragraph is indeed 320px. It's not smaller as you think, because width of the .outer container is bigger due to padding.

By default actual element width is a sum of the width + padding + border.

You want it to be smaller? Then add box-sizing: border-box rule to .outer container:

.outer {
    /* ... */
    box-sizing: border-box;
}

Demo: http://jsfiddle.net/f2br8ppw/4/

Upvotes: 0

Related Questions