Rajat Gupta
Rajat Gupta

Reputation: 26607

css way to make appear list elements <li/> with certain class on top of list

Is there any css way to bubble up <li> elements with some class on top of list. I guess I have come across some way to do this in the past but cant remember how to do this exactly.

Please note I dont need to rearrange in markup. Just make the elements with certain class appear as if on top of other elements without that class.

Can anyone tell if there is some way to do this?

Upvotes: 0

Views: 276

Answers (1)

Maloric
Maloric

Reputation: 5625

With pure CSS, you can move an element to the top of the list using absolute positioning, though it would not actually be at the top of the list as far as the markup is concerned. What you want to do can be achieved with javascript however. Using jQuery, you would want to do something along these lines:

HTML:

<ul id="myList">
    <li>Second</li>
    <li>Third</li>
    <li>Fourth</li>
    <li class="top">First</li>
    <li>Fifth</li>
</ul>

Javascript:

$(document).ready(function () {
    var list = $('#myList');
    list.children('li.top').remove().prependTo(list);
});

Working example: http://jsfiddle.net/tMWJs/

Edit:

To do this with pure CSS, use absolute positioning. Here is an example of the css you would need:

ul#myList {position:relative; margin-top:40px;}
ul#myList li {line-height:20px;}
li.top {position:absolute; top:-20px;}

If you have multiple elements to move, this approach would need tinkering to position each element seperately, and is probably not suitable.

Working example: http://jsfiddle.net/sp73f/

Upvotes: 2

Related Questions