Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I center something if I don't know ahead of time what the width is?

I am trying to center a paragraph tag with some text in it within a div, but I can't seem to center it using margin: 0 auto without having to specify a fixed width for the paragraph. I don't want to specify a fixed width, because I will have dynamic text coming into the paragraph tag and it will always be a different width based on how much text it is.

Does anyone know how I can center the paragraph tag within the div without having to specify a fixed width for the paragraph or without using tables?

like image 679
zeckdude Avatar asked Dec 10 '22 20:12

zeckdude


2 Answers

Here's how to do it using a style sheet.

Style sheet:

div.center-content
{
    text-align: center;
}

div.center-content p
{
    text-align: left;
    margin-left: auto;
    margin-right: auto;
}

HTML:

<div class="center-content">
    <p>Lorem ipsum dolor sit amet</p>
</div>
like image 175
Garry Shutler Avatar answered Dec 29 '22 01:12

Garry Shutler


Found this: Centering Block-level Content With Unknown Width.

like image 25
drdaeman Avatar answered Dec 29 '22 00:12

drdaeman