将 <div>-Container 放在 margin:auto 居中 <div> 的右侧

Place <div>-Container on the right side of a margin:auto centered <div>

我想将一个 div 放在另一个 div 的右侧,后者以 margin:auto 为中心。 (像侧边栏)

简单HTML:

#c1{
 background-color:#CCCCCC;
    width:300px;
    margin:auto;

}

#c2{
 background-color:#BBBBBB;
 width:100px;   
 }
    <div id="c1">con1</div>
    <div id="c2">con2</div>

我已经尝试了这个问题的解决方案,但它在我的 fiddle 中不起作用。第二个 div 在下一行。 Link: positioning elements left and right of a div with margin:auto

如何解决这个问题?

您可以使用定位来创建此效果:

#c1{
    background-color:#CCCCCC;
    width:300px;
    margin:auto;
    position:relative;
}

#c2{
    background-color:#BBBBBB;
    width:100px;
    position:absolute;
    right:-100px;
    top:0;
}

然后您需要重新排列 HTML 使其看起来像这样:

<div id="c1">
    con1
    <div id="c2">con2</div>
</div>

使用 position 属性 并在 DOM 中稍加节制,您可以轻松实现这一目标。

这是代码

  .wrapper {
        position: relative;
        width: 100%;
        padding:0;
        margin:0;
    }
    #c1 {
        background-color:#CCCCCC;
        width:300px;
        margin:auto;
        height:100px;
        position: absolute;
        left:0;
        right:0;
        top:0;
    }
    #c2 {
        background-color:#294596;
        width:100px;
        height:100px;
        position: absolute;
        left:0;
        top:0;
    }
    <div class="wrapper">
       <div id="c1">con1</div>
       <div id="c2">con2</div>
   </div>

它将为您解决问题。

HTML:

<div id="c1">
    con1
    <div id="c2">con2</div>
</div>

CSS:

#c1 {
    background-color:#CCCCCC;
    width:300px;
    margin:auto;
    position: relative;
}

#c2 {
    background-color:#BBBBBB;
    width:100px;
    position: absolute;
    right: -100px;
    top: 0px;
}

这里是JSFiddle