开发者

Placing a div sidebar next to a centered div

开发者 https://www.devze.com 2023-02-14 00:43 出处:网络
I\'ve found a lot of variations to this question within SO, but it seems no matter what I try I can\'t get this (seemingly very simple!) thing working!

I've found a lot of variations to this question within SO, but it seems no matter what I try I can't get this (seemingly very simple!) thing working!

What I'm trying to do is to keep the 'centered' div in the center of the viewport and to place the 'sidebar' div directly to its right (i.e. not right-aligned to the viewport) without affecting the centering of the 'centered' div.

Here's some test code on jsfidd开发者_JAVA技巧le:

http://jsfiddle.net/6wCyr/13/

Everything I've read seems to imply that the float property is exactly what I'm looking for, but the results in the link show that I get weird results wherein the right sidebar is placed below the 'centered' div rather than beside it. That's what's shown in the link.

I've also seen a solution involving using a negative value for the right property, and setting the width of the sidebar exactly, but I couldn't get that one going either.

Hopefully this question is as easy to solve as I think it should be! Just can't seem to find the right set of div inside div and so forth. Hard to debug these alignment issues!

Thanks!


Live Demo

  • I moved div.sidebar inside div.centered.
  • I added position: relative to div.centered.
  • We're using this technique.
  • You don't have to declare a fixed width on div.sidebar.

CSS:

div.centered {
    margin-left: auto;
    margin-right: auto;
    border: dashed;
    width: 100px;
    height: 100px;
    position: relative
}

div.sidebar {
    border: dotted;
    position: absolute;
    top: 0;
    left: 100%
}

HTML:

<div class="holder">
    <div class="centered">
        CENTERED
        <div class="sidebar">
            RIGHT SIDEBAR
        </div>
    </div>
</div>


Try this.

http://jsfiddle.net/DOSBeats/6wCyr/16/

.holder {
    margin:0 auto;
    width:100px;
}

.centered {
    border: dashed;
    float:left;
    height: 100px;
}

.sidebar {
    border: dotted;
    float:left;
    margin-right:-100px;
    width:100px;
}


If you do not set a width to your holder and center it, the sidebar will float to the edge of the window.

Try this:

HTML:

<div id="holder">
<div id="sidebar">Sidebar</div>
<div id="centered">Centered</div>
</div>

CSS:

#holder{
  margin:auto;
  width:500px;
}
#sidebar{
  border:dotted;
  float:left;
  width:100px;
}
#centered{
  border:dashed;
  margin-left:110px;
  width:380px;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消