nyxthulhu
nyxthulhu

Reputation: 9762

CSS Centering with div to the left of another div

So what I'm trying to accomplish is to have a div centered on the page (margin: auto auto;) with a navigation div just to the left of it.

The idea being the navigation div can be switched on or off (so may or may not be there). If its there or not should not interferer with the centering of the main div.

Below is an example

Mockup Image

I've tried a few things

Any pointers would be appreciated in the best way to do this. I was hoping to avoid tables.

JSFiddle link

Upvotes: 3

Views: 133

Answers (2)

ProtoWeapon
ProtoWeapon

Reputation: 56

Try this:

In your html:

<body>
<div class="encasing">
    <div class="leftmenu"></div>
</div>
</body>

In your css:

html, body
{
  width: 100%;
  height: 100%;
}

div.encasing
{
  top: 50px;
  margin-left: auto;
  margin-right: auto;
  width: 70%;
  height: 500px;
  background-color: green;
  position: relative;
}

div.leftmenu
{
  right: 100%;
  width: 10%;
  height: 300px;
  background-color: red;
  position: absolute;
}

The important parts are:

  • To put your block containing the menu inside your center block
  • Make the center block have margin-left: auto; margin-right: auto;
  • Make the center block have a relative positioning
  • Have the menu have a absolute positioning
  • Make the menu have right: 100%

The idea here is to make the left menu use the position of the center block and then adjust itself. Right: 100% will put the right edge of the menu on the left edge of the menu.

In the end, a really good trick in css is that absolute positioned elements adjust themselves relative the the nearest relative or absolute positioned parent. :)

Upvotes: 2

tdammers
tdammers

Reputation: 20706

A few solutions I can think of:

  • Use absolute positioning for the navigation div. You probably want to give the body element a min-width to avoid the navigation div overlapping the main div when the window is too small.
  • Three-column layout, e.g. two divs with fixed widths floated to the left and right, and the content div between them. Inside the left-floated div, display your navigation div (or not). Alternatively, try display: inline-block on the three columns. The difference is in how small windows are handled (try it out). Again, you can counter undesired effects by setting a min-width on the body.
  • Completely fixed layout. Decide on an ideal screen resolution, and hard-code everything to that. This way, you can absolute-position everything where you want it, but the downside is that it won't look good on anything that deviates too much from the intended resolution. Especially mobile devices will see devastating results; you counter these with @media queries to adjust your layout to other screen resolutions.

You should also try to find a site that does what you want to do, and see how they did it (inspect HTML, CSS, and maybe Javascript).

Upvotes: 0

Related Questions