Search code examples
htmlcssalignment

How to select a paragraph that contains a floating image?


I'd like to be able to write a CSS rule that applies to a paragraph, but only if that paragraph contains an <img> tag with an align attribute. Note I do not want to select the image, but the paragraph that contains it. (I want to apply the style clear: both to the paragraph to make sure there is room for the floating image in the margin.) Is this possible using only CSS rules supported by current browsers?

Currently I'm actually munging the HTML generated by a help tool using a post-processing script I wrote, but doing it with CSS would be far more elegant and less trouble-prone.


Solution

  • CSS doesn't have any parent selectors, only descendant. You would have to use javascript to select the img tag and then call getParent() on it.

    in Mootools javascript library:

    $('p img[align=*]').getParent();
    

    See Also:

    CSS selectors: http://www.w3.org/TR/CSS2/selector.html#descendant-selectors