【问题标题】:How can I make a div's contents wrap without setting an explicit width?如何在不设置显式宽度的情况下使 div 的内容换行?
【发布时间】:2011-06-30 23:44:47
【问题描述】:

我想要一系列带有标题和其他信息的帖子。问题是,根据包含的 div 有多少空间以及标题有多长,它会导致我的“post-summary”(标题、日期等)div 换行到下一行,使其看起来像:

这是它正在做的事情:

这是我想要它做的(注意标题被包裹,但没有导致整个“post-summary”像前面的例子一样包裹到下一行):

我不在乎标题换了多少或换了多少行。我只是不希望它像第一个示例中那样强制包含帖子信息的父 div 低于帖子编号。

我创建了一个示例 jsfiddle 来进一步说明我在做什么: http://jsfiddle.net/aZvVU/6/

我怎样才能让帖子标题在没有足够空间的情况下简单地换行,并且不会导致整个“post-summary”div 下降到下一行?如果可以避免的话,我不想固定标题宽度。

【问题讨论】:

  • 你的意思是如果行长于可用空间,它应该显示... 省略号
  • 不,我只是希望它自然地换行到下一行,但不强制其父 div “post-summary”中断到下一行。因此,发布日期和标题仍将位于灰色帖子编号框的右侧。

标签: html css layout width


【解决方案1】:

您可以以此为起点http://jsfiddle.net/A8csU/

HTML:

<div id="parent">
    <div id="right-child">
        <p>Right stuff.</p>
    </div>
    <div id="left-child">
        <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It  has roots in a piece of classical Latin literature from 45 BC, making it  over 2000 years old. Richard McClintock, a Latin professor at  Hampden-Sydney College in Virginia, looked up one of the more obscure  Latin words, consectetur, from a Lorem Ipsum passage, and going through  the cites of the word in classical literature, discovered the  undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33  of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by  Cicero, written in 45 BC. This book is a treatise on the theory of  ethics, very popular during the Renaissance. The first line of Lorem  Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section  1.10.32.</p>
    </div>
</div>

CSS:

#left-child {
 border: 1px solid red;
    margin-right: 102px; /* 100px + 1px border + 1px border */
}

#right-child {
    width: 100px;
    border: 1px solid blue;
    float: right;
}

【讨论】:

  • 你能看看我提供的小提琴吗?我不确定您在此处显示的内容是否真的适用。进行这些相同的调整仍然会导致帖子摘要低于帖子编号。
【解决方案2】:

您可以像这样对代码进行一些调整:

.post-list
{
    float: left;
    margin-right: 250px;  /* make sure it doesn't touch your right-nav*/
}

.right-nav
{
    background-color: #c0c0c0;
    padding: 10px;
    min-height: 300px;
    width: 200px;
    position: absolute; right: 0px; top: 0px; /* position it */
}

这是一个工作示例,您的代码为http://jsfiddle.net/YumSP/

已编辑以修复标题换行 http://jsfiddle.net/YumSP/1/

【讨论】:

  • 那行不通。 post-summary div(包含 post-title 和 post-info)被包裹到 post-number 下方。
  • 编辑了 CSS。该示例现在适用于包装标题等。
  • @Viquinish 如果 'float:left' 对您不起作用,您需要将您的 jsfiddle.net 示例放在这方面以获得进一步的帮助。
【解决方案3】:

将浮动放在.post-summary 上,你不需要它,它会导致你的包装。然后将margin-left: 40px; 添加到.post-summary 以确保.post-number 有空间,并为.post-number 提供全高柱的错觉,而不必担心高度。

要整理导航栏,请从.post-list 中删除浮动并关闭您的清理&lt;div&gt;s。如果您希望导航栏占据一整列,请将margin-right:220px 添加到.post-list

例如:

【讨论】:

    猜你喜欢
    • 2017-12-20
    • 2010-12-21
    • 2015-08-21
    • 2013-06-09
    • 2019-09-10
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多