Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Have container fit the width of one of its children, and another children using text-overflow

Have container fit the width of one of its children, and another children using text-overflow

Problem

I'm looking for a way to have a HTML Container Fit the Width of one of its children.

OK I know, this is how it already works by design.

But! I also need another children to collapse with a "text-overflow: ellipsis". Problem is: to apply such a property, you need this children to be in "display: block" mode, which makes it enlarge the container width.

Is there any secret time to achieve what I'm looking for.

Here is a JsFiddle in case you don't get it or want to give it a try.

Edit : by the way, and this is important, I'm targetting specifically Internet Explorer 10.

Problem courtesy of: user1174017

Solution

As watson said, there is no "shrink-to-fit" css rule. So, you have two choices:

  1. Set the size of the .overflow elements manually and statically. So, instead of width:100%, you put width:330px.

  2. Use javascript to resize the .overflow elements dynamically. (I'm assuming you have more than one.) You said you wanted to shrink to the biggest internal div. Let's say you have several divs you might want to shrink to, but you want to shrink to the largest of them. First, you set them all to a class like this:

    .good-width{
        border: solid 2px salmon;
        width:auto; /* necessary for some browsers' offsetWidth */
        display:inline-block; /* gives it the width of the contents */
    }
    

And you put javascript something like this at the top of the page:

var goods = document.getElementsByClassName('good-width');
//collect the widest one's width
var maxwidth = 0;
for(var x = 0; x  maxwidth) {
        maxwidth = goods[x].offsetWidth;
    }
}
//set the width of the overflow divs to match
var overflows = document.getElementsByClassName('overflow');
for(var y = 0; y 

If I misunderstood, and you're trying to match specific overflows to specific good-widths, you should assign each element an id and do things that way:

document.getElementById('overflowID').style.width = document.getElementById('good-widthID').offsetWidth + 'px';

If it were my website, I would actually combine both #1 and #2, in order to have it look at least decent for those who don't have javascript. That is, you set a static width to the overflow things that isn't too far off, then allow the javascript to overwrite it if it can.

Solution courtesy of: miyasudokoro

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

Have container fit the width of one of its children, and another children using text-overflow

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×