Find first element in div that has margin? (purpose: remove margin)

I need to find the first (and last) element in a div that has a CSS margin set (> 0 px). (important: this is not necessarily the first or last element!)

Basically, I need to do this so that I can remove the margin-top for the first element and the margin-bottom for the last. Now I know you'll probably say "why not use "p:last" CSS syntax?"

Because the first or last element can be something else as well, it could be a list (UL, OL), an image, a paragraph, etc.. I cannot simply do, ul:last, ol:last, p:last as that could result in multiple elements being matched (one per type).

I only want to apply this to a single element. So that's why I think jquery is the only solution. I would gladly be wrong on this though.

Answers


Since you want only the first/last child with a margin, I imagine you'll need to use jQuery/JavaScript:

var isfirst = 1, lastelm;
$("#divid").find("*").each(function() {
    var cur = $(this);
    if(parseInt(cur.css("margin-top")) > 0 && isfirst == 1) {
        cur.css("margin-top", 0);
        isfirst = 0;
    }
    if(parseInt(cur.css("margin-bottom")) > 0) {
        lastelm = cur;
    }
});
lastelm.css("margin-bottom", 0);

Need Your Help

How do I make my Windows Azure application resistant to Azure datacenter catastrophic event?

azure cloud reliability

AFAIK Amazon AWS offers so-called "regions" and "availability zones" to mitigate risks of partial or complete datacenter outage. Looks like if I have copies of my application in two "regions" and one

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.