Search code examples
htmlcsslayoutcentermultiple-columns

Centering inside a variable size container that is not full width?


I've found many answers to centering a variable size div, but I want to center a div inside a variable size div. I haven't been able to find any help on this matter.

Essentially, my wrapper is divided into two columns. Left one with a fixed width and right one that is supposed to fill in the rest of the screen. I've got this worked out.

Now, I would like to place another div in the middle (both vertical and horizontal) of the right column. You can find an illustration of my goal HERE.

THIS is what I've got so far:

HTML:

<div class="wrapper">
  <div class="header">     
  </div>
  <div class="right">
    <section role="main">
      <article>
        <h1>Title</h1>
          <p>Paragraph</p>
      </article>
    </section>
  </div>
</div>

LESS:

html, body { 
    height: 100%;
    margin: 0;
    padding: 0;
}

body {
    background: #333;
    font: normal normal 12px/18px @font;
    color: @text;   
}

.wrapper {
    width: 100%;
  min-width: 800px;
    height: 100%;
}

.header {
    float: left;
    width: 250px;
    height: 100%;
    background: @c2;
}

.right {
  margin-left: 250px;
    background: @c1;
    height: 100%;

    article {
    height: 300px;
        width: 500px;
        background: #fff;
    }

}

My goal is to get the white article -element in the middle of the yellowish one.

What I've tried:

  • display:table -technique found at emergentweb.com/test/valign.html
  • ghost-child -technique fount at css-tricks.com

Is this even possible?

I don't really mind JS / jQuery, but I'd prefer not to use them.


Solution

  • Try adding this css property

    .right article{
    margin:auto;
    }
    

    Or you can do this.

    If the div you want to center is 500px, do this.

    To the parent div, apply position:relative and to de div you want to center apply

    .right article{
    position:absolute;
    left:50%;
    margin-left:-250px;
    }
    

    This mechanism also works for vertical centering.