简体   繁体   中英

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

I want to position a div on the right side of a other div which is centered via margin:auto. (Like a sidebar)

Simple 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>

I have tried the solution from this question but it does not work in my fiddle. The second div is in the next line. Link: positioning elements left and right of a div with margin:auto

How to solve this?

You can use positioning to create this effect:

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

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

And then you need to rearrange the HTML to look like this:

<div id="c1">
    con1
    <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;
}

Here is JSFiddle

Using position property and a little moderation in your DOM you can easily achieve this.

Here's the Code :

 .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>

It will do the trick for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM