Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using percentage values to fill flexbox items

I use flexboxes in Google Chrome (only this browser has to be supported) to create a dynamic layout. I've got n child elements in one div element which should share the whole space with all the same ratio. This is working without problems due to the new introduced flex-boxes. But I also had to set the height of each inner div to 0. If I want to stretch an element inside this div to 100% height it uses the given value of 0 instead of any computed value. As I've chosen flex-boxes in order to prevent using javascript I would prefer remaining that way. Is there any other way to make the image's height filling the div?

And here is the code (only tested in Google Chrome):

html

<div class="flexbox">
    <div><img src="chrome-logo.png" /></div>
    <div><img src="chrome-logo.png" /></div>
    <div><img src="chrome-logo.png" /></div>
    <div><img src="chrome-logo.png" /></div>
</div>

css

            .flexbox {
                display:-webkit-box;
                -webkit-box-orient:vertical;
                height:300px;
                width:200px;
            }
            .flexbox > div {
                -webkit-box-flex:1;
                height:0;
                border:solid 1px #000000;
            }
            .flexbox > div > img {
                height:100%;
            }

The code to watch in the browser

like image 934
Louis Avatar asked Dec 26 '11 08:12

Louis


People also ask

How do you calculate flex percentage?

The flex item size is computed and added to the size of the space it is to take, then the other items sizes are then computed. The percentage value tells the flex item to grow 2% or 3% of the parent's width. With a flex-grow of 1, all the flex items will share the available spaces equally: (700 / 3) = 233.3px .

How do I fill my flexbox space?

You can use the flex-grow property to force an item to fill the remaining space on the main axis of a flex container. The item will expand as much as possible and occupy the free area.

How do you make a flex item full width?

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100% , and enable wrap on the container. The item now consumes all available space.


1 Answers

Well I got it working after hours of research. The following changes are to do:

.flexbox {
            display:-webkit-box;
            -webkit-box-orient:vertical;
            height:300px;
            width:200px;
        }
        .flexbox > div {
            -webkit-box-flex:1;
            height:0;
            border:solid 1px #000000;
            position:relative; /* CHANGE */
        }
        .flexbox > div > img {
            height:100%;
            position:absolute; /* CHANGE */
        }

If you're intrested in you can make these changes via the ChromeDevTools to the css and you'll see the right result!

like image 64
Louis Avatar answered Oct 25 '22 18:10

Louis