【问题标题】:How to achieve Bottom Align floated div that sizes to it's container如何实现底部对齐浮动 div 大小与其容器
【发布时间】:2011-01-13 18:01:38
【问题描述】:

如何实现以下布局?具体ImageDIV的定位

我发现除非我为 Div 设置特定的宽度,否则它只会继续到下一行并占据容器的整个宽度。此外,将其相对于图像底部对齐给我带来了麻烦。目前他们都是float:left

编辑:到目前为止,如果图​​像的宽度是恒定的,我想我可以使用这两种解决方案,但它是在作者个人资料页面的 Wordpress 主题中进行的,并且图像的宽度可能会略有不同。无论图像有多宽或多窄,是否有一种解决方案可以让 Div 位于图像旁边(减去填充)?基本上让 div 调整其宽度以适应图像宽度。

【问题讨论】:

    标签: css vertical-alignment


    【解决方案1】:

    在 IE7/8、Firefox、Chrome 中测试。

    Live Demo #2

    CSS:

    #container{width:80%; padding:12px; margin:0 auto}
    #top{position:relative;overflow:auto}
    #top img{float:left; background:red; width:100px; height:180px}
    #header{position:absolute; bottom:0; right:0}
    #content{height:200px}
    

    JS/jQuery:

    $('#header').css('margin-left', $('#top img').width() + 10);
    

    (您可能想将+ 10 更改为parseInt($('#top img').css('margin-right'), 10)

    HTML:

    <div id="container">
        <div id="top">
            <img src="" />
            <div id="header">Some text here that should wrap to fit on row. Some text here that should wrap to fit on row. Some text here that should wrap to fit on row. Some text here that should wrap to fit on row. </div>
        </div>
        <div id="content">dfgdfg</div>
    </div>
    

    【讨论】:

    • 事先不知道图片宽度可以吗?
    • 这可能是可能的,但肯定会更复杂。它用于“Wordpress 主题”这一事实意味着您应该有 jQuery/JS 可用。因此,我认为最简单的解决方案是给#header 一个margin-left,无论图像使用JS 有多宽。你觉得怎么样?
    • 理想情况下我更喜欢纯css,但如果不存在纯css解决方案,我不反对JS解决方案。
    • Here's a version 使用JS;您可以更改#top img 的宽度并按运行查看它。现在我知道你想要什么了,如果到那时还没有其他人解决它,我明天会尝试一个纯 CSS 解决方案。
    • JS 解决方案看起来很棒。可能想把它放在你的答案中。如果明天某个时候没有可接受的纯 CSS 解决方案出现,我会接受你的。
    【解决方案2】:

    我会将标题图像和标题 div 放在它自己的容器中,并使用绝对定位来定位其中的项目。

    我在这里整理了一个快速示例:http://jsfiddle.net/JjxYj/1/

    这里注意,如果去掉header中Div的宽度,就会变成其内容的宽度。

    更新

    为了回答问题的更新部分,这是另一个解决方案,它允许图像具有任何宽度,同时仍将标题文本定位在其包含项目的底部:http://jsfiddle.net/JjxYj/5/

    【讨论】:

    • 更新的解决方案仅在文本看起来适合一行时才有效。标题文本实际上有一个&lt;h2&gt; 和一个&lt;p&gt;。我正在使用&lt;h1&gt;Some text here that should wrap to fit on row.&lt;/h1&gt; &lt;p&gt;Some text here that should wrap to fit on row. Some text here that should wrap to fit on row. Some text here that should wrap to fit on row.&lt;/p&gt; 进行测试。
    • 这是一个很好的解决方案。有用。使用position: absolute; bottom: 0;,其中相邻元素具有position: relative; 将解决问题。只要记住在移动设备上将位置设置回staticfloatnone
    猜你喜欢
    • 2010-09-23
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 2011-09-01
    • 2010-10-09
    • 2016-12-08
    • 1970-01-01
    相关资源
    最近更新 更多