在绝对定位元素周围包装文本

时间:2013-06-20 10:46:11

标签: javascript jquery html css css3

我遇到了一些我有大量带有消息框的内容页面的东西。在此消息框中,您可以拥有图像,文本,标题等。但是每个消息框的框右上角都有一个图标。如果我使用position:absolute,图像将位于框的顶部。但是,如果消息框有标题或段落,并填充框的宽度。文本将位于图像下方。

我基本上需要一个带有宽度的图像包装器,因此文本只能坐直到图像的边缘。我99%肯定通过将绝对定位的图像包裹在div中并给它一些样式来使它在firebug中工作。但我今天似乎无法让它发挥作用!

有数百页,因此不能选择移动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在图像周围包裹了一个div

CSS:

.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小提琴 - http://jsfiddle.net/jdp7E/

3 个答案:

答案 0 :(得分:8)

纯CSS解决方案:使用

在容器的开头添加一个伪元素
div.message:before { content:" "; float:right; width:75px; height:75px; }

http://jsfiddle.net/jdp7E/1/

不适用于不支持生成内容的旧浏览器,因此主要是旧版IE。对于那些容器的填充权可以用作后备。

答案 1 :(得分:0)

嗯,也许是一个非常快速的解决方案,但是如何将padding-right设置为“.message”呢?

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

<强> Working fiddle

答案 2 :(得分:0)

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+"%");