【问题标题】:CSS let input consume available widthCSS让输入消耗可用宽度
【发布时间】:2012-09-07 15:29:14
【问题描述】:

我有以下标记作为基础:

<div>
    <span>some dynamic text</span>
    <input type="text" />
</div>

我希望输入与文本一起显示在一行中(始终是单行但长度不同),并根据文本长度消耗可用宽度。如果需要,可以更改标记。两个元素都应该是父元素宽度的 100%。

【问题讨论】:

    标签: css text input


    【解决方案1】:

    我能想到的两种方法:

    第一个:

    您可以使用 CSS 模拟表格的行为;

    HTML:

    <div class = "container">
        <div class = "text">Glee is awesome!</div>
        <div class = "inputtext"><input type="text" /></div>
    </div>
    

    CSS:

    .container {
        display: table;
        width: 100%; /*how much should both the text and the input take*/
    }
    .container .text {
        white-space: nowrap;
        display: table-cell;
        width: 1px; /*make sure it's only as wide as needed*/
    }
    .container .inputtext {
        display: table-cell;
    }
    .container input {
        width: 100%; /*let the input take all available space*/
    }
    

    小演示:little link.

    第二个:

    此方法依赖于浮动:

    HTML:

    <div class = "text">Glee is awesome!</div>
    <div class = "inputtext"><input type = "text" /></div>
    

    CSS:

    .text {
        float: left;
    }
    .inputtext {
        overflow: hidden; /*this is the key here*/
    }
    input {
        width: 100%;
    }
    

    另一个小演示:little link

    【讨论】:

    • 基本上它工作得很好,只是一件不可爱的事情:输入的右边框丢失了。好像 1px 太宽了:见这里jsfiddle.net/AWHEn/1
    • @AndreasLinden 是的,那是因为宽度设置为 100% 然后你添加了一个 1px 边框,所以有一个 2px 溢出。您可以将宽度设置为99%,我不知道这是否足够好。我会继续寻找更美丽的东西。
    • @j08691 什么都没有 :) 我也想到了这个,我想我也可以发布它。
    • @j08691 更新了答案,现在包含这两种方法。
    • @AndreasLinden @j08691 好吧,除了设置width: 99%,我想不出任何办法。抱歉:(当然,一种方法是完全避免设置边框。
    猜你喜欢
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    相关资源
    最近更新 更多