nluigi
nluigi

Reputation: 1345

Horizontally aligning inner `divs`

I am looking to horizontally (and preferably vertically) align three inner divs. Applying margin: 0 auto; to class vbox should do the trick but as in the following minimal code, it isn't affecting the alignment at all. How can i accomplish this aligning?

HTML:

<body>
  <div id='site'>
    <div class='main'>
      <div class='vbox'>
        <div id='inner1'>inner1</div>
        <div id='inner2'>inner2</div>
        <div id='inner3'>inner3</div>
      </div>
    </div>
  </div>
</body>

CSS:

#site {
  width: 100%;
  height: 100%;
}

#main {}

.vbox {
  margin: 0 auto;
}

The result can be seen in this fiddle.

Upvotes: 1

Views: 47

Answers (6)

Gautam
Gautam

Reputation: 1

You could do this to align all 3 divs vertically by using:

#site {
  width: 100%;
  height: 100%;
}

#main {}

.vbox {
  margin: 0 auto;
}

.vbox div{
  width: 30%;
  float: left;
}

If you have more divs or less, just update the width accordingly.

Upvotes: 0

aphextwix
aphextwix

Reputation: 1858

You could do this :

HTML

<body>
  <div id='site'>
    <div class='main'>
      <div class='vbox'>
        <div class='inner'>inner1</div>
        <div class='inner'>inner2</div>
        <div class='inner'>inner3</div>
      </div>
    </div>
  </div>
</body>

CSS

 #main {
  width: 100%;
}

.vbox {
  width: 500px;
  margin: 0 auto;
  text-align: center;
}

.inner {
  display: inline-block;
  margin: 0 4px;
}

Upvotes: 0

Adam D Harrington
Adam D Harrington

Reputation: 353

Try something like this

#site {
  width: 100%;
  height: 100%;
}

#main {
  Width:100%;
}

.vbox {
  margin: 0 auto;
  padding:0;
}
.vbox div{
  width:32%;
  display:inline-block;
  padding:0;
  margin:0;
  box-sizing:border-box;
}

The important bit is that the default behavior of a div is to take up the full width of its parent. To change this you give it the display mode inline-block.

Upvotes: 0

oboshto
oboshto

Reputation: 3627

You can use display: inline-block for your inner divs:

.vbox {
  text-align: center;
  font-size: 0; /* white spaces fix */
}

.vbox > div {
  font-size: 1rem; /* white spaces fix */
  display: inline-block;
}

Example

Upvotes: 0

ketan
ketan

Reputation: 19341

Just give display: table; to .vbox will make it horizontal center.

.vbox {
  margin: 0 auto;
  display: table;
}

Working Fiddle

Another solution is display: flex;

.main {
    display: flex;
}

Fiddle

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You need to define the width for vbox:

.vbox {
  margin: 0 auto;
  width: 30%;/*apply as your own*/
}

100% wide element is centered horizontally but you see no alignment for text. For this you should apply text-align: center;

Upvotes: 3

Related Questions