开发者

Centered DIV with extra content on one side

I have 开发者_如何转开发an inner div centered horizontally within a container div, and I need to add another div within that container, to the right of the centered div? How can I do so without disturbing the position of the centered div (i.e. it should still be centered in the container, not between the left edge of the container and the left edge of the other div?

<div id="container">
    <div id="inner"></div>
    <div id="right"></div>
</div>

div#container {
    width: 960px;
}
div#inner {
    width: 400px;
    margin: 0 auto;
}
div#right {
    width: 100px;
    float: right;
    /* what else? */
}

Ideally, I would even want to specify the position of div#right as a distance from the right edge of div#inner, rather than using float:right.

(The only solution I've thought of so far is to add another div on the left with the same width as div#right and set visible:none. Is there a better way?)


I would try absolute positioning within the parent <div>:

div#container
{
  width: 960px;
  position: relative;
}

div#inner
{
  width: 400px;
  margin: 0px auto;
}

div#right
{
  position: absolute;
  width: 100px;
  right: 0px;
  top: 0px;
}

No guarantees on whether this will work out-of-the-box, but I would try something like this.


Add an extra wrapper for both of them and use that for relative positioning.

<div id="container">
  <div id="center">
    <div id="inner">Some</div>
    <div id="right">content</div>
  </div>
</div>

Then use the new centered as relative positioning and "hang" the right one on that. Use a negative margin-right to get it outside.

div#container {
    width: 960px;
    background: red;
}
div#center {
    width: 400px;
    margin: 0 auto;
    position: relative;
}
div#inner {
    background: blue;
}
div#right {
    width: 100px;
    background: pink;
    position: absolute;
    right: 0;
    top: 0;
    margin-right: -100px;
}


Because you're explicitly setting the widths of your container and inner divs, you can center the inner div by setting it's left margin to an exact pixel length (rather than using margin: auto, which is only needed for containers of indefinite or variable width). You know your container is 960px, and your inner is 400px, so centered it would have 280px on either side.

Then float: left both inner and right divs. You can vary the gutter width between inner and right by setting right's margin-left too.

Try this (verified in Firefox)(you'll need either content in the divs or their heights set to see the results, of course):

div#container {
width: 960px;
}
div#inner {
width: 400px;
margin-left: 280px;
float: left;
}
div#right {
width: 100px;
float: left;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜