Search code examples
htmlcsspositioningcss-position

html + CSS: Make position relative some other element?


I'm building a tree using lists in lists the ordinary way. Now, what I would like to do is to have an extra label that is absolute (horizontally) to the start of the outermost tree.

The effect I'm trying to achieve is the below, where the farLeft are labels on each li (see similar html below):

Tree

I can easily do this, but my css will be unclean, to say the least, something along the lines of:

/* each indentaion level is 20 px to teh right, so I need to offset */
ol.topLevel li label.farLeft { position absolute; left=-218px; ...}
ol.topLevel li ol li label.farLeft { position absolute; left=-238px; ...}
ol.topLevel li ol li ol li label.farLeft { position absolute; left=-258px; ...}

A usage could be like the below, but with more nesting levels:

<ol class="topLevel">
  <li>
     <label>Some niceLabel</label>
     <label class="farLeft">Far left text</label>
  </li>
  <ol>
     <li>
        <label>Some niceLabel</label>
        <label class="farLeft">Far left text</label>
      </li>
  </ol>  
</ol>

The above sucks in many ways, notably I have to change value in plenty of places if I move something, and I have to make one line per indention level.

Is there a better way to solve this, perhaps make my 'left' being the left of my top level tree, or some other good html mechanism.

It might be the time to mention I'm a total css newbie, so I might easily have missed somethnig completely obvious.


Solution

  • Here its fiddle link

    http://jsfiddle.net/5YKFa/6/

    css

    ol.topLevel{
        padding-left: 100px;
    }
    li{
        padding-left: 20px;
    }
    .left {
        position: absolute; left:0px;
    }
    

    html

    <ol class="topLevel">
      <label>Top Level</label>
      <li>
         <label class="left">Label</label>
         <label>1</label>
      <ol>
         <li>
           <label class="left">Label</label>
           <label>1.1</label>
         </li>
         <li>
           <label class="left">Label</label>
           <label>1.2</label>
         </li>
      </ol>  
      </li>
    </ol>