Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Float with multiline content: Minimal width

Is it possible to have a floating element that has multiline content to take minimal width?

Floating elements without a set width use up the least amount of width as long as their content is just one line. If it is more than one line, the width of the element is 100%.

My 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>

My 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;
}

My fiddle

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

My image

enter image description here

like image 648
yunzen Avatar asked Sep 27 '13 11:09

yunzen


1 Answers

this is a solution using JQuery

you can see this Working Fiddle Tested On: IE10, IE9, IE8, FireFox, Chrome, Safari

HTML: (I changed it a little bit)

<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);
});

Edit: a little bit more of Scripting to adjust the gray container as well As can be seen at this Working Fiddle

like image 77
avrahamcool Avatar answered Oct 14 '22 12:10

avrahamcool