Eagle
Eagle

Reputation: 1565

How to center horizontally div inside parent div

How do I center a div horizontally inside its parent div with CSS?

<div id='parent' style='width: 100%;'>
 <div id='child' style='width: 50px; height: 100px;'>Text</div>
</div>

Upvotes: 144

Views: 242459

Answers (7)

David Spector
David Spector

Reputation: 1671

If you don't want to use flex, but just want to center an element, you can create a parent div for the element, without changing anything else, like this:

<div id=OriginalParent>
    <div id=InsertedNewParent> (style: width:100%; text-align:center)
        <myelement>
    </div>
</div>

The width:100% means make the new parent exactly as wide as the original parent. The text-align:center centers myelement within InsertedNewParent. Why is the style called text-align:center when <myelement> might not be text? Just history.

Upvotes: 1

Grigor Nazaryan
Grigor Nazaryan

Reputation: 577

.parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child-canvas {
  flex-shrink: 0;
}

Upvotes: 12

Paul Chris Jones
Paul Chris Jones

Reputation: 2909

Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>   

Upvotes: 7

x4u
x4u

Reputation: 14077

You can use the "auto" value for the left and right margins to let the browser distribute the available space equally at both sides of the inner div:

<div id='parent' style='width: 100%;'>
   <div id='child' style='width: 50px; height: 100px; margin-left: auto; margin-right: auto'>Text</div>
</div>

Upvotes: 4

James Goodwin
James Goodwin

Reputation: 7406

<div id='parent' style='width: 100%;text-align:center;'>
 <div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
</div>

Upvotes: 13

Mark Embling
Mark Embling

Reputation: 12821

I am assuming the parent div has no width or a wide width, and the child div has a smaller width. The following will set the margin for the top and bottom to zero, and the sides to automatically fit. This centers the div.

div#child {
    margin: 0 auto;
}

Upvotes: 202

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>

Upvotes: 2

Related Questions