Mark
Mark

Reputation: 5108

Center divs horizontally within container div

I have multiple divs which are a set width and I want to center within a container div. The number of child divs may vary so I need them to center no matter how many divs are withing the parent div. Note: the container div must have position:absolute

<div class="wrapper">
  <div class="f" ></div>
  <div class="f" ></div>
  <div class="f"></div><div class="f">
  </div><div class="f"></div>
</div>

And the CSS

.wrapper {
    position: absolute;
    width: 80%;
    top: 0;
    left: 0;
    text-align: center;
    margin: 0px auto;
    border: 0.2rem solid black;
    height: 0.8rem;
}

.f {
    -webkit-box-shadow: inset 0.2rem 0 0 white;
    box-shadow: inset 0.2rem 0 0 white;
    background-color: red;
    width: 35px;
    height: 0.8rem;
    position: relative;
    float: left;
}

The jsfiddle is here

Upvotes: 1

Views: 82

Answers (2)

SW4
SW4

Reputation: 71240

Remove the float and set display:inline-block on the children, then remove the height from the container so it auto expands as necessary.

Demo Fiddle

CSS

.wrapper {
    position: absolute;
    width: 80%;
    top: 0;
    left: 0;
    text-align: center;
    margin: 0px auto;
    border: 0.2rem solid black;
}
.f {
    -webkit-box-shadow: inset 0.2rem 0 0 white;
    box-shadow: inset 0.2rem 0 0 white;
    background-color: red;
    width: 35px;
}
i {
    font-size: 0;
    height: 0.8rem;
    position: relative;
    display:inline-block;
}

Upvotes: 1

Hushme
Hushme

Reputation: 3144

Simple add this css

JSFIDD

    .wrapper {
position: absolute;
width: 80%;
top: 0;
left: 0;
text-align: center;
margin: 0px auto;
border: 0.2rem solid black;
height: 0.8rem;
    left:50%;
    margin-left: -40%; /*width/2*/
}

Upvotes: 0

Related Questions