A vertical list of items where each line compresses its width to fit inside the content

I want to create a vertical list where each line compresses its width to fully contain its internal content (compared to the default behavior of a div to expand its width to fill the container).

I would like to do this with only one HTML element for each line (without additional wrapping divs).

The following code does exactly what I want, but it does not work in Safari (error?).

 .container { margin: 10px; border: 2px solid #999; padding: 5px; display: flex; flex-direction: column; width: 300px } .row-item { padding: 5px; margin: 5px; border: 1px solid green; /* this will shrink the width to the inner content in Chrome and Firefox, but not in Safari */ margin-right: auto; } 
 <div class='container'> <div class='row-item'>Item #1</div> <div class='row-item'>Another Item...</div> <div class='row-item'>Item No. 3</div> </div> 

Here is the code with the code above: http://codepen.io/anon/pen/woKYqx

I know that solving this problem is trivial by adding a wrapper div and then using display: inline-block for the inner element (or several other similar solutions).

However, it seems that this should be possible to solve without adding extra HTML elements. This is a pretty simple layout.

Is there a cross-browser way to do this with one HTML element for each line?

+5
source share
3 answers

You use margin-right: auto to move the whole element to the left, which also forces the element to take the width of its content.

This is a good method, but as you already noted, it does not work in Safari.

A simple alternative is to use align-self: flex-start for flex items:

 .row-item { padding: 5px; margin: 5px; border: 1px solid green; align-self: flex-start; /* NEW */ /* margin-right: auto; (can be kept or removed) */ } 

OR, just use align-items: flex-start in the flex container.

 .container { margin: 10px; border: 2px solid #999; padding: 5px; display: flex; flex-direction: column; align-items: flex-start; /* NEW */ width: 300px } 
+5
source

You can remove all flex elements and use float:left and clear:left for child elements and overflow-x: hidden for parent:

http://codepen.io/anon/pen/pNjQJJ

+2
source

When you use display: flex, you should also use the vendor prefixes for it. too old browsers support if in doubt check caniuse.com

 .container { display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */ display: -webkit-flex; /* NEW - Chrome */ display: -ms-flexbox; /* TWEENER - IE 10 */ display: flex; /* ETC */ } 

NOTE: caniuse.com wrote about height flexbox error messages for children on safari.

-1
source

Source: https://habr.com/ru/post/1259530/


All Articles