【问题标题】:How to make a inner div width fit text when outer div fixed width and scroll horizontally?当外部div固定宽度并水平滚动时,如何使内部div宽度适合文本?
【发布时间】:2012-09-15 15:27:26
【问题描述】:

HTML

<div class="outer">
    <ul>
        <li>
            <div>text</div>
        </li>
        <li>
            <div>longlonglonglonglonglonglonglonglonglonglonglonglong</div>
        </li>
    </ul>
</div>

CSS

.outer {
    width: 300px;
    height: 200px;
    background-color: #ddd;
    overflow: scroll;
}

li {
    margin: 5px;
}

li>div {
    cursor: pointer;
    height: 30px;
    line-height: 30px;
    border: 1px solid #369;
    background-color: #fff;
}

JSFiddle

需要:

内部 div 宽度适合文本。文本只是单行。并且内部 div 不使用固定宽度。

像这样(这个demo LI的margin无效。) JSFiddle

【问题讨论】:

  • 只需要在一行中显示吗?
  • UPDATE2:我想要:JSFiddle 但内部 div 宽度不固定。
  • 所以你希望所有的内部 div 在外部 div 内的宽度相同,在一行中显示文本?
  • @venkateshwar 是的,一行。对不起,我只是没有看到你的评论。
  • 查看我的answer's link。希望您满意。

标签: html css text width


【解决方案1】:

嗨,现在习惯了

word-break: break-all;

.....

li>div {
    word-break: break-all; // add this line
    height:30px; // remove this line
}

删除 height 在您的li&gt;div

live demo

来自演示的 HTML

<div class="outer">
    <ul>
        <li>
            <div>text</div>
        </li>
        <li>
            <div>longlonglonglonglonglonglonglonglonglonglonglonglong</div>
        </li>
    </ul>
</div>

演示中的 CSS

.outer {
    width: 300px;
    height: 200px;
    background-color: #ddd;
    overflow: scroll;
}

li {
    margin: 5px;
}

li>div {
    cursor: pointer;
    line-height: 30px;
    border: 1px solid #369;
    background-color: #fff;
     word-break: break-all;
}

【讨论】:

  • 对不起,我不想中断文本。
【解决方案2】:

HTML

<div class="outer">
    <ul>
        <li>
            <div>text</div>
        </li>
        <li>
            <div>longlonglonglonglonglonglonglonglonglonglonglonglong</div>
        </li>
    </ul>
</div>

CSS

.outer {
    width: 300px;
    height: 200px;
    background-color: #ddd;
    overflow: scroll;
}

li {
    margin: 5px;
}

li>div {
    cursor: pointer;
    height: 30px;
    width:400px;
    line-height: 30px;
    border: 1px solid #369;
    background-color: #fff;

}

检查这个Fiddle

如果你不想破坏文本,那么你可以使用overflow-x:scroll属性

【讨论】:

  • 内部 div 不使用固定宽度。
  • 请明确说明您的问题。编辑您的问题并使其理解。这样我们就可以回答了。 @consatan
  • 对不起,怪我表达不清楚。非常感谢!!(对不起我的英语......)
【解决方案3】:

float:left;
margin:5px;

在 li>div 样式中

DEMO

DEMO 2

【讨论】:

    猜你喜欢
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多