-1

I'm trying to get div #primary to sit in the middle of the page with position: relative and margin: 0 auto, and I also want to have an <aside> element that sits directly to the right of #primary and does not shift around on width resize.

With margin: 0 auto, I notice in Chrome/Firefox Developer Tools that this effectively gives #primary full margins on either side, preventing anything from entering that space.

I tried giving #primary float: left, but this seems to cancel out the margin: 0 auto and makes #primary flush against the left side of the page.

How can I achieve this effect? Thanks.

#content {
  margin: 0 auto;
  width: 100%;
}

#primary {
  position: relative;
  width: 900px;
  margin: 0 auto;
}

aside {
  width: 350px;
  float: right;
}
<div id="content">

  <div id="primary"></div>

  <aside></aside>

</div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
rpivovar
  • 3,150
  • 13
  • 41
  • 79

1 Answers1

1

Just place aside above/before that centered DIV in your HTML code (I changed the dimensions of the elements to make it fit into the snippet window):

#content{
    margin: 0 auto;
    width: 100%;
    height: 500px;
    background: yellow;
}

#primary{
    position: relative;
    width: 300px;
    height: 300px;
    margin: 0 auto;
    background: red;
}

aside {
    width: 100px;
    height: 200px;
    float: right;
    background: green;
}
<div id="content">
    <aside>aside</aside>

    <div id="primary">primary</div>


</div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
  • Thanks! I'll accept this as the correct answer when it lets me...why does this work though? – rpivovar Dec 18 '17 at 23:16
  • 1
    because `float: right` means that other elements can float around it (text) or next to it (blocks) at the left side - but beginning at its position in the code, not before that (i.e. it will not move up even if there is space) – Johannes Dec 18 '17 at 23:22
  • Cool, thanks. I guess it takes it out of the flow? Found this answer helpful, too https://stackoverflow.com/a/32301823/7386637 – rpivovar Dec 18 '17 at 23:23