user1115666
user1115666

Reputation:

center left aligned text using javascript/jquery

Basically what I'm trying to do is to center all of the left aligned text based on the width by getting the width of each then making the left margin negative half of whatever the width was but right now it's only applying to the first paragraph.

I tried using inline-block so that the width is accurate to the text and not the inherited width of the parent? I still want block elements to behave like block elements though.

How can I get this to apply to all of the text when the page loads?

Also, I want this to work for all of the text on a page (p, li, pre, blockquote) is there a better way of doing this? I could just list everything in the function I guess.

<html>
<head>
<title>center left aligned text using javascript/jquery</title>
<style type="text/css" media="screen">

* {
    margin: 0;
    padding: 0;
}

#container {
    margin: 200px auto;
    width: 1280px;
    height: 800px;
    border: #000 1px solid;
}

#container p {
    background: #eee;
    display: inline-block;
    left: 50%;
    max-width: 500px;
    position: relative;
}

</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function () {

    $(function() {
        var width = $("p").width();
        $('p').css('margin-left', -width / 2);
    });

}); 

</script>
</head>
<body>
<div id="container">
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
    <p>Lorem ipsum dolor sit amet.</p>
</div>
</body>
</html>

EDIT: If I insert a block element after each, it behaves correctly

$("p").each(function () {
    var width = $(this).width();
    $(this).after('<br />');
    $(this).css('margin-left', -width / 2);
});

Upvotes: 0

Views: 2693

Answers (2)

Popo
Popo

Reputation: 2460

I think this will be about as close as you can get unless you add more formatting/elements to the markup:

http://jsfiddle.net/sanpopo/rQG8c/

$(document).ready(function () {
   $('p').each(function() {
      var width = $(this).width();   
       alert(width);
       $(this).css({'margin-left': -width / 2, 'text-align': 'center'}).after('<br /><br />');    
   });
}); 

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

You need an .each() loop to find the width and apply the margin to each paragraph individually:

$("p").each(function () {
    var width = $(this).width();
    $(this).css('margin-left', -width / 2);
});

http://jsfiddle.net/mblase75/Cg45A/

That said, as long as you have inline-block applied to the paragraphs, I don't think they're going to look anything like the way you want them to. What exactly is your end design supposed to look like?

Upvotes: 1

Related Questions