DextrousDave
DextrousDave

Reputation: 6793

Center align a div that has no width defined

Very simple question: What is the CORRECT way of center aligning a div that has no set width? Doing this for a div:

.class div{
    margin: 0 auto; 
    width: 300px;
}

will align the div horizontally center, but NOT if you remove the set width.

However, this does the trick, but is it the correct way?

.class div{
    margin: 0 auto; 
    display: table;
}

Thank you!

Upvotes: 1

Views: 346

Answers (1)

sandeep
sandeep

Reputation: 92793

Write like this:

HTML

<div class="parent">
 <div class="class"></div>
</div>

CSS

.parent{
 text-align:center;
}
.class{
    display:inline-block;
    text-align:left;
}

Upvotes: 5

Related Questions