Bjorn J
Bjorn J

Reputation: 642

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.

Upvotes: 1

Views: 4085

Answers (3)

Utku Yıldırım
Utku Yıldırım

Reputation: 2277

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>

Upvotes: 2

Jeff Lauder
Jeff Lauder

Reputation: 1247

Is the 'farLeft class being used elsewhere on the page? If not, the easy solution would be:

.farLeft { position: absolute; left:0px; ...}

Absolute positioning should line up automatically with it's parent container at 0px. So if you wrap a relatively positioned div around it you should be able to adjust margins and whatnot to get the result you are looking for.

You don't need to specify where everything is in the dom structure, unless you only want it to apply there, and even then using an id on the tag would be a better solution. Good luck

Upvotes: 1

twaggs
twaggs

Reputation: 3733

You can probably just use a margin on each level of the nesting, so it will grow the deeper you go.

Upvotes: 1

Related Questions