开发者

How to select a paragraph that contains a floating image?

开发者 https://www.devze.com 2023-03-24 17:25 出处:网络
I\'d like to be able to write a CSS rule that applies to a paragraph, but only if that paragraph contains a开发者_开发百科n <img> tag with an align attribute. Note I do not want to select the im

I'd like to be able to write a CSS rule that applies to a paragraph, but only if that paragraph contains a开发者_开发百科n <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.


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


There are no CSS selectors that allow you to do this (what is essentially a look-behind selection). The best options you have for cross-browser support would be:

  1. Adding JS to your page to detect the floated image, and then apply a css class to the parent paragraph.
  2. Modify the code in place (if at all possible) to add a css class to the parent paragraph for any floated images.


I don't think so. The idea of support for a 'contains' attribute has been dropped, as browsers don't support selecting parents of the selector.

It would be fairly easy to do this in jQuery: http://jsfiddle.net/2u7fg/1/

$('p').each(function() {
     if ($(this).find('img').attr('align').length)
         $(this).css('background', 'red');
});

EDIT: hopefully less verbose version (I'm sure there's a better way of doing this)...

$('img').filter(function() { return $(this).attr('align').length > 0; }).parent().css('background', 'red');

http://jsfiddle.net/2u7fg/2/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号