【问题标题】:CSS: Float with multiline content: Minimal widthCSS:具有多行内容的浮动:最小宽度
【发布时间】:2014-01-19 03:58:53
【问题描述】:

是否可以让具有多行内容的浮动元素占用最小宽度?

只要内容只有一行,没有设置宽度的浮动元素使用的宽度最少。如果超过一行,则元素的宽度为 100%。

我的 HTML

<div class="wrap">
    <div class="floater"> <a class="left" href="#">
            <span class="right">Right<br>Right<br>Right</span>
            <span class="inner">Left: longword longerword evenlongerword longerword evenlongerword longword.
            </span>
        </a>
    </div>
</div>

我的 CSS

.wrap {
    width: 350px;
    border: 1px solid gold;
}
.floater {
    overflow: hidden;
    padding: 10px;
}
.left {
    float: left;
    border: 1px solid silver;
    padding: 5px;
}
.right {
    float:right;
    margin: 0 10px;
    border: 1px solid green;
    padding: 5px;
}
.inner {
    border: 1px solid red;
    display: block;
    overflow: hidden;
    padding: 5px;
}

我的小提琴

http://jsfiddle.net/HerrSerker/qBfbc/

我的头像

【问题讨论】:

  • 如果不是 100% 宽,为什么任何代码会以完全一样的方式而不是以其他方式分配单词?
  • @Itay 我也想到了。也许有一种解决方法不适用于浮动。
  • 您对 jQuery 解决方案感兴趣吗?
  • 您必须在左侧或内部容器上设置大约 270px 的宽度才能包裹单词,否则它只会使用尽可能多的空间来容纳单词现有空间。
  • 您的意思是right 类嵌套在left 中,还是一个错误?

标签: html css css-float


【解决方案1】:

这是一个使用 JQuery 的解决方案

你可以看到这个Working Fiddle 测试于: IE10、IE9、IE8、FireFox、Chrome、Safari

HTML:(我稍微改了一下)

<div class="wrap"><a href="#">
        <span class="right">
            Right
            <br />
            Right
            <br />
            Right
        </span>
        <span class="inner">Left: longword longerword evenlongerword longerword evenlongerword longword.
        </span>
    </a></div>

CSS:

*
{
    padding: 0;
    margin: 0;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.wrap
{
    width: 350px;
    padding: 10px;
    border: 1px solid gold;
}

.wrap a
{
    display: inline-block;
    width: 100%;
    height: 100%;
    border: 1px solid silver;
    padding: 5px;
}
.right
{
    float: right;
    border: 1px solid green;
    padding: 5px;
    margin-left: 10px;
}
.inner
{
    border: 1px solid red;
    display: block;
    overflow: hidden;
    padding: 5px;
}

jQuery:

$.fn.textwidth = function () {
    var html_org = $(this).html();
    var html_calc = '<span>' + html_org + '</span>';
    $(this).html(html_calc);
    var width = $(this).find('span:first').width();
    $(this).html(html_org);
    return width;
};

$(document).ready(function () {
    $(".inner").width($(".inner").textwidth()+2);
});

编辑:更多的脚本来调整灰色容器 可以在Working Fiddle

看到

【讨论】:

  • 它以某种方式起作用,但并不完全正确。重要的是,“右”元素紧挨着左元素。
  • @HerrSerker 看看这个Fiddle
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
  • 2022-07-26
相关资源
最近更新 更多