每次我尝试在 CSS 中做一些看似简单的事情时,它都不起作用。
我有一个包含 460x160 图像的内容 div。我想要做的就是将图像放在右下角,然后将我的文字环绕在它周围。
<div id="contents">
<img src="..." />
text text text text text text ...
</div>
所以我希望它看起来像:
------------------
| text text text |
| text text text |
| text text -----|
| text text | |
------------------
用左上角或右上角的图像做这件事很简单:
#contents img { float:right; }
------------------
| text text | |
| text text -----|
| text text text |
| text text text |
------------------
现在我该如何将其推到底部?到目前为止我想出的最好的是:
#contents img { float:right; margin-top: 90%} // really needs to be 100%-160px
------------------
| text text |
| text text |
| text text -----|
| text text | |
------------------
在这种情况下,文本不会打印在页边空白处,因此图像上方有空白区域。
#contents { position:relative; }
#contents img { position:absolute; right:0; bottom:0; }
-or-
// move the img tag under the text in the html and:
#contents img { float:right; margin-top:-160; }
------------------
| text text text |
| text text text |
| text text -----|
| text text | te |
------------------
在这种情况下,文本打印在图像上方或下方。
那么…我怎样才能做到这一点?
原文由 CodingWithSpike 发布,翻译遵循 CC BY-SA 4.0 许可协议
它肯定似乎 在 (2003) 之前、 (2002) 之前或 (2005) 之前 被问过
最后一个链接实际上建议了一个 基于 javascript 的解决方案,但是对于一个固定的(即非流动的)解决方案。
然而,它与 发现的其他建议 是一致的
或者 这个:
无论如何,正如 本线程中所讨论的那样,没有简单的解决方案……
Cletus 在 2003 年的评论中提到了这个线程,它再次说明了它不容易实现的事实。
但是,它确实参考了这篇 Eric Meyer 的文章,它接近您想要达到的效果。
然而, Chadwick Meyer 在 他的回答 中提出了一个基于
:before
CSS 选择器( Leonard 的 回答 的变体)的解决方案。它在 这里工作。
2021 年 4 月更新: Temani Afif 在 他的回答 中建议使用 Flexbox 结合 shape-outside。
但是一定要检查 Flexbox 的向后兼容性,尽管所有浏览器 对它的支持 都非常好。