1

I would like my ad div to be exactly between the left side of the body, and the middle div. How would I accomplish that?

body {
border: 1px solid black; 
}
#middle {
border: 1px solid black;   
margin: auto;  
width: 50px;
height: 100px; 
} 
#ad {
border: 1px solid black;
float: left;    
width: 50px;
height: 100px; 
}
<div id = "ad"> ad </div>
<div id = "middle"> middle </div>
frosty
  • 2,559
  • 8
  • 37
  • 73
  • 1
    What do you mean by "exactly between"? I am afraid you need to specify the exact layout you want. – Joy Dec 03 '15 at 02:51
  • @Joy I mean the ad div with a margin of auto, that's between the left side of the body, and the center div. – frosty Dec 03 '15 at 02:52
  • the problem is, that your `margin: auto` is orientated at the other elements (your parent element). You could achieve this but it will be hacky...better define no-relative sizes or use a kind of responsive design here – messerbill Dec 03 '15 at 02:54

1 Answers1

1

You can achieve this layout with flexbox, combining auto margins with an invisible flex item.

HTML

<div class="box ad"> ad </div>
<div class="box middle"> middle </div>
<div class="box invisible"> right </div><!-- invisible -->

CSS

body {
  display: flex;
  border: 1px solid black;
}

.box {
  width: 50px;
  height: 100px;
  border: 1px solid black;
}

.invisible { margin-left: auto; margin-right: auto; visibility: hidden;  }
.middle    { margin-left: auto; }
.ad        { margin-left: auto; }

DEMO

Note that flexbox is supported by all major browsers, except IE 8 & 9. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add all the prefixes you need, post your CSS in the left panel here: Autoprefixer.

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701