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);
});
inline-block
. Fiddle: jsfiddle.net/fEa4J Did I miss something?