在绝对定位元素周围换行文本

Wrapping text around an absolute positioned element

本文关键字:周围 换行 文本 元素 定位      更新时间:2023-09-26

我被困在一个带有消息框的内容页面上。在这个消息框中,你可以有图像,文本,标题等。但是,每个消息框的右上角都有一个图标。如果我使用position:absolute,图像将位于框的顶部。但是,如果消息框有标题或段落,并以框的宽度填充。文本将位于图像的下方。

我基本上需要一个包装周围的图像有一个宽度,所以文字只会坐起来,直到图像的边缘。我99%肯定我得到了它的工作在firebug通过包装绝对定位的图像在一个div和给它一些风格。但是我今天好像不能用它了!

有数百个页面,所以移动HTML不是一个选择。该图像目前没有包装器。所以我不得不使用Jquery来包装图像。(如果这就是答案的话)。

我知道绝对位置将元素置于文档流之外,但是我能做些什么吗?

无论如何,这是我到目前为止的代码:

<div class="message">
<h3>Some text, a header perhaps? But this is the next that will sit under the image, sometimes it's a p tag.</h3>
<img class="messageIcon" src="/link-to-icon/which-are-the-same-size" border="0" width="64" >
<p>Some more random text that would appear in the messagebox this could go on for a few lines.</p>
</div>

<script type="text/javascript">
$(document).ready(function(){
    $('img.messageIcon').wrap('<div class="messageIconWrap" />');
    alert("this is a test");
});

</script>

JS在图像

周围包装一个divCSS:

.messageIconWrap{
    display: inline-block;
    float:right;
    height:60px;
    width:60px;
}
div.message {
    position: relative;
}
.message {
    background: none repeat scroll 0 0 #393939;
    clear: both;
}
.messageIcon {
    position: absolute;
    right: 20px;
    top: 20px;
    float: right;
}

JS Fiddle - http://jsfiddle.net/jdp7E/

纯CSS解决方案:在容器的开头添加一个伪元素

div.message:before { content:" "; float:right; width:75px; height:75px; }
http://jsfiddle.net/jdp7E/1/

不能在不支持生成内容的旧浏览器中工作,所以主要是旧的IE。对于这种情况,可以使用容器的右填充作为回退。

嗯,也许是一个非常快速的解决方案,但是如何设置padding-right为"。"消息"是这样的?

div.message {
    position: relative;
    padding-right:80px; /* - You can set a padding higher or equal than the image - */
}
工作小提琴

jsFiddle Demo

我的建议是计算文本信息的宽度,计算图标的宽度,将文本信息的宽度设置为图标宽度从文本信息宽度中移除后的剩余百分比。

var mw = $('.message:first-child').width();
var iw = $('.messageIcon').width() + 20;//20 is for padding
var percent = parseInt((mw - iw) / mw * 100);
$('.message :first-child').width(percent+"%");