3

To make this easy, say you had a div that was 100px wide, and 3 divs inside of it each 20px wide. How can I align them to where they align to the center of the div leaving a 20px; gap on each side?

2
  • to make it even more easy you can post a JSFiddle Commented Apr 14, 2013 at 23:43
  • Is anything known ahead of time other than the size of the parent div? Are the actual child divs variable-width? Is there a variable number of child divs? Commented Apr 15, 2013 at 0:27

2 Answers 2

4

Center some HTML elements always depends of your project and integration dependencies...

You may be happy with these 2 solutions, display: inline-block; and float: left;

Both have pros & cons, hope that it can help you !

http://jsfiddle.net/HP2DS/1/

<!-- Inline-block -->
<div id='container'>
    <div class='centered' id='content-left'></div><div class='centered' id='content-center'></div><div class='centered' id='content-right'></div>
</div>

#container {
    width: 100px;
    height: 80px;
    text-align: center;
    background: cyan;
}

#container .centered {
    display: inline-block;
    width: 20px;
    height: 100%;
    margin: auto;
    background: magenta;
    border: 1px solid black;
    box-sizing: border-box;
}

<!-- Floating -->
<div id='container-2'>
    <div class='centered' id='content-2-left'></div>
    <div class='centered' id='content-2-center'></div>
    <div class='centered' id='content-2-right'></div>
</div>

#container-2 {
    width: 60px; /* 60px + 2*20px of padding... */
    height: 80px;
    padding: 0 20px;
    text-align: center;
    background: cyan;
}

#container-2 .centered {
    float: left;
    width: 20px;
    height: 100%;
    margin: auto;
    background: magenta;
    border: 1px solid black;
    box-sizing: border-box;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Good day! Here is how I implemented it:

HTML

<div id="container">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

CSS

#container {
  width: 100px;
  height: 100px;
  border: 1px solid red; /** for viewing purposes **/
  text-align: center; /** center the divs **/
  font-size: 0; /** remove the unwanted space caused by display: inline-block in .child **/
}

#container .child {
  display: inline-block; /** set the divs side-by-side **/
  vertical-align: top;
  width: 20px;
  height: 100px;
  font-size: 12px; /** override font-size: 0 of #container, so that text will be visible again **/
  text-align: left; /** set text in the .child divs back to normal alignment **/
  border: 1px solid blue; /** for viewing purposes **/
  box-sizing: border-box;
}

I hope this helps. Cheers! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.