Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center align a div that contains floated elements?

I need inner_holder to have width of 960px and I need it to be centered. I tried using width: 960px and margin: 0px auto but it doesn't work. How can I center the divs inside inner_holder?

HTML:

<div class="parent_container">
    <div class="inner_holder">
        <div class="column column1">
            <div class="inner_clip"></div>
        </div>
        <div class="column column2">
            <div class="inner_clip"></div>
        </div>
        <div class="column column3">
            <div class="inner_clip"></div>
        </div>
    </div>
</div>

CSS:

.parent_container {
      height: auto;
      margin: 15px auto;
      min-height: 500px;
      width: 960px;
}
.column {
     float: left;
     margin-right: 50px;
}
.inner_clip {
    background-color: #333333;
    height: 250px;
    margin-bottom: 20px;
    width: 250px;
}
like image 927
ariel Avatar asked Sep 09 '13 18:09

ariel


People also ask

How do I center a floated div?

You can set float div center by using margin property. you does not need to use float property but you can use margin property and set left or right margin value auto by this way.

How do you center a floated element in CSS?

The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout.

How do you center a div and its contents?

With CSS, you can center text in a div in multiple ways. The most common way is to use the text-align property to center text horizontally. Another way is to use the line-height and vertical-align properties. The final way exclusively applies to flex items and requires the justify-content and align-items properties.

How do I make my div centered?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.


1 Answers

As you can see here the "div that contains floated elements" is actually in the center (red).

I am assuming you want to center the floating elements themselves, not their parent. I'm afraid you can't do that (as far as I know). But in case you are not depending on your elements actually floating, you propably just want to display your .colum as inline-block with an text-align:center set to the parent.

Changes to your CSS:

.parent_container {
    text-align:center;     // added
}
.column {
    display: inline-block; // added
    margin: 0 25px;        // added
    float: left;           // removed
    margin-right: 50px;    // removed
}

Result as Fiddle

like image 119
RienNeVaPlu͢s Avatar answered Oct 13 '22 11:10

RienNeVaPlu͢s