简体   繁体   中英

flex box make items 100% width of itself

I have the following html structure which I'm trying to arrange with a flex-box approach, with a row flex-direction. This is more or less the idea

<!-- 100% viewport width -->
<body>

    <!-- This toolbar should have whatever width may remain from parent -->
    <div class="toolbar-1 width-remain">

        <!-- This toolbar should have whatever width may remain from parent -->
        <div class="tb1-item1 width-remain">Some content</div>

        <!-- This toolbar should have 100% of its content -->
        <div class="tb1-item2 width-content">
            <!-- This toolbar should have 100% of its content -->
            <div class="tb1-item2-inner1 width-content">Some content</div>
            <!-- This toolbar should have 100% of its content -->
            <div class="tb1-item2-inner2 width-content">Some content</div>
            <!-- This toolbar should have 100% of its content -->
            <div class="tb1-item2-inner3 width-content">Some content</div>
        </div>

        <!-- This toolbar should have 100% of its content -->
        <div class="tb1-item3 width-content">Some content</div>
    </div>

    <!-- This toolbar should have 100% of its content -->
    <div class="toolbar-2 width-content">
        <div class="tb2-item1 width-content">Some content</div>
    </div>
</body>

I was hoping to have two toolbars where one may grow in width (the second one, and the first one may occupy whatever space is left). Also, inside the first toolbar I have some extra items which I'd like to be able to grow in width, and one item which may occupy whatever space is left).

In general the width set in the inner items as flex: 1 1 100%; takes the 100% of its parent, and not of its width. Setting flex: 1 1 auto; makes the items to have an even width. Also tried putting 0 to the flex-growth and flex-shrink properties. I've tried setting justify-content: stretch; to the toolbar parent, and justify-self: stretch to the inner items that may grow based on its content but with no success.

does anyone know how I can achieve this? Thanks in advance!

It sounds like there's a misunderstanding on how to use the flex property with child elements within an element with display:flex; .

Essentially you need to tell .toolbar-1 it's okay to grow, and .toolbar-2 it's okay to shrink. To accomplish that you can certainly use the flex property like so:

.toolbar-1 {
  flex: 1 0 auto; /* grow shrink basis */
}
.toolbar-2 {
  flex: 0 1 auto;
}

Alternatively you can just use the grow and shrink properties:

.toolbar-1 {
  flex-grow: 1;
}

.toolbar-2 {
  flex-shrink: 1;
}

I threw together this example based on what I understand from the question: Flexible Toolbars

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM