居中浮动div
我被卡住了。这是我正在做的事情,我在网页上的主图像旁边有一个AddThis共享窗口小部件。图像更改大小,我需要AddThis以动态更改其与图像的位置。我在another question问过这个问题,通过另一个论坛我可以得到一些帮助。现在AddThis和图像对齐正确,一切似乎都朝着正确的方向,但图像不再居中。我需要这个图像集中在页面上,但我不知道如何做到这一点,因为我不得不浮动包含图像和AddThis的div。这里是HTML:居中浮动div
<div class="feature-container">
<div style="min-height:100px; min-width:100px; position:relative; float:left; ">
<div style="text-align:center;"><img class="feature-image"
src="/Images/test.jpg" width="300px;" alt="test" /></div>
<div style="position:absolute; bottom:0px; right:-40px;">
<div class="addthis_toolbox addthis_floating_style addthis_16x16_style">
<a class="addthis_button_facebook"></a>
<a class="addthis_button_twitter"></a>
<a class="addthis_button_email"></a>
<a class="addthis_button_compact"></a>
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/300
/addthis_widget.js"></script>
</div>
</div>
</div>
任何想法如何居中?我可以使用直接的CSS解决方案或使用jQuery和CSS的解决方案。请提供例子。
Here is a page这是我尝试使用的最新代码。
试试这个:
var pos = $('.center').width() - $('img').width();
$('.center').css('margin-left', pos);
我之前提出的评论似乎已经消失。如果出现两次,我很抱歉。我实现了你的JS,它的工作原理,但创造了一些其他的错误。图片下方的内容被抛弃,页面非常宽,与940px的宽度相符。我编辑了小提琴以包含这些额外的内容,并且我添加了带有最近代码的页面的链接。谢谢你的帮助。 – L84
@Lynda欢迎您。试试这个:'$('。center').css('margin-left',pos/2)';如果你的容器的宽度是940px,图像的宽度是300px,你可以通过计算(940-图像的宽度(300))=> 640px/2 => 320px,所以'margin-left:320px',我可以看到你的最上面的包装不居中,如果你想正确地居中元素,你应该居中包装:'margin:0 auto'; – undefined
它有一个轻微的故障!在我摆弄它从中提取信息的时候,你的评论中的代码起作用。我创建了另一个div来包装图像和AddThis代码,而不是使用'.center'。然后,而不是使用'$('img')。width();'我添加了一个类到主图像并使用它。现在我能看到的唯一问题是主图像和它下面的徽标略偏离中心。它可能偏离20px,但它是显而易见的。任何想法如何纠正?注:小提琴已更新。 – L84
我不知道你的“IM-中心”的内容,因为我添加的内嵌样式(文本对齐:中心;)如下,测试它和IE 8
<div class="img-center" style="text-align:center;">
<img src="test.jpg" alt="test" />
</div>
工作正常
定义中心div的固定宽度可以,如果这不是一个固定的宽度,@ Raminson的jquery解决方案更好。我真的很想知道,如果我们能够实现这个纯CSS
<div id="top" class="wrap_fullwidth">
<div class="center" style="width:400px;">
<div style="min-height:100px; min-width:100px; position:relative; float:left; ">
<div style="text-align:center;"><img src="http://www.ubhape2.com/Images/test.jpg" alt="test" /></div>
<div style="position:absolute; bottom:0px; right:-40px;">
<div class="addthis_toolbox addthis_floating_style addthis_16x16_style">
<a class="addthis_button_facebook"></a>
<a class="addthis_button_twitter"></a>
<a class="addthis_button_email"></a>
<a class="addthis_button_compact"></a>
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/300/addthis_widget.js"></script>
</div>
</div>
</div>
</div>
_ “我不得不浮动DIV” _ - 为什么?我不知道如果没有看到一些周围的元素,我可以提出任何建议。 – nnnnnn
@nnnnnn - 这是AddThis的行事方式。为了使它相对于图像的位置,它必须被漂浮。 – L84
你能提供[jsfiddle](http://jsfiddle.net)上的示例吗? – undefined