如何选择包含浮动图像的段落?
我希望能够编写适用于段落的 CSS 规则,但前提是该段落包含带有 align
属性的
标记。注意我不想选择图像,而是选择包含它的段落。 (我想对段落应用 clear: Both
样式,以确保页边空白处有浮动图像的空间。)仅使用当前浏览器支持的 CSS 规则是否可以实现这一点?
目前,我实际上正在使用我编写的后处理脚本来修改帮助工具生成的 HTML,但使用 CSS 来完成会更加优雅并且更不容易出现问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
CSS 没有任何父选择器,只有后代选择器。您必须使用 javascript 选择 img 标签,然后对其调用 getParent() 。
在 Mootools javascript 库中:
另请参阅:
CSS 选择器: http://www. w3.org/TR/CSS2/selector.html#descendant-selectors
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:
See Also:
CSS selectors: http://www.w3.org/TR/CSS2/selector.html#descendant-selectors
没有 CSS 选择器允许您执行此操作(本质上是后视选择)。跨浏览器支持的最佳选择是:
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:
我不这么认为。支持“包含”属性的想法已被删除,因为浏览器不支持选择选择器的父级。
在 jQuery 中做到这一点相当容易:
http://jsfiddle.net/2u7fg/1/
编辑:希望更简洁的版本(我是当然有更好的方法来做到这一点)...
http://jsfiddle.net/2u7fg/2/
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/
EDIT: hopefully less verbose version (I'm sure there's a better way of doing this)...
http://jsfiddle.net/2u7fg/2/