Search code examples
htmlcsspositioning

CSS positioning relative over fixed/absolute


Apologies if I appear quite "noobish" with CSS. I've been trying to set the following...

#0 {
 width: 100%;
 height: y;
 border: 1px solid black;
}   
#a {
 position: fixed;
 float left;
 width: x;
 height: y;
 border: 1px solid black;
}
#b {
 position: relative;
 float: left;
 width: x;
 height: y;
 border-right: 1px solid black;
}

/* HTML */
<div id="0">Some div...</div>
<div id="a">Another div</div>
<div id="b">Final div...</div>

For some reason, if I attempt to position #b below #a, #b will appear ontop of #a unless I declare its position as either static or absolute, but will then be required to manually position the top/left properties, and this doesn't display properly for all browsers either. Any help would be greatly appreciated!

Have got it fixed now! (had to declare html, body:( width: 95%;)) Thanks for all the advice guys!


Solution

  • First of all, a couple of fixes: #0 needs to be named something else, because IDs cannot start with a number. You're also missing a : in the float property for #a. Not sure what's with the 'x' and 'y' for the height/width, either - I assume those are just examples?

    Fixed and Absolute elements are out of the document flow. That is, they don't take up space as far as normal positioned elements.

    Therefore, the fixed element will have the relative one over it in your example, as you found because they can inhabit the same x-y space. If you had it as absolute, top:0; left: 0, the same thing would happen.

    Next, you had one as a float (almost), so let's consider that float changes all of that positioning. Floats are 'special' in the way they are laid out. They are in the flow, but will be as far up and in the float direction as possible. If they're too wide to fit next to other floated content on that line, they go to the next line.

    You could do

    <style>
     #a
      {
      float:left;
      height:100px;
      width:150px;
      background-color:black;
      }
      #b
      {
      clear:left;
      height:100px;
      width:150px;
      background-color:green;
      }
     </style>
     <div id='a'>aaaaa aaa</div>
     <div id='b'>bbb bbb</div>
    

    'Clear' means an element will appear beneath preceding elements that are floated. #b will be on the next line, underneath #a. You could also make #a have a big margin on the right, or be wide enough to fill whatever container and not leave room for #b, to make #b be beneath #a instead of next to it.