简体   繁体   中英

How to get an absolutely positioned item inside a relatively positioned flexbox container to grow?

Here's a jsfiddle: https://jsfiddle.net/wwucLo3c/ I need the red div to be full width when there is no cyan div. And if there is they both have to be 50%.

Here's the container's CSS:

.container{
    position:relative;
    width:100%;
    height:100%;
    background:blue;

    display:flex;
    flex-direction:row;
    align-content:stretch;
}

And the item's:

.item{
    position:absolute;
    top:10%;
    flex:1 1 1;
    min-width:50%;
    height:10%;
}

Basically, i need an absolutely positioned item to grow if there is no other item at it's width and shrink if there is. Is it even possible? It seems like i tried every flexbox setting and nothing helped.

Is it even possible?

No , You cannot set flex layout properties(except order) to flex children with position: absolute

Absolutely-Positioned Flex Children

An absolutely-positioned child of a flex container does not participate in flex layout. However, it does participate in the reordering step (see order), which has an effect in their painting order.


Solution:

  1. Remove position: absolute and change the position using margin-top .
  2. flex: 1 1 1 is incorrect. The last value flex-basis does not accept unit-less values(except 0 and auto)

Updated JSfiddle

 body { width: 300px; height: 600px; margin: 0; } html { width: 100%; height: 100%; } .container { position: relative; width: 100%; height: 100%; background: blue; display: flex; flex-direction: row; align-content: stretch; } .item { flex: 1 1 0; height: 10%; margin-top: 10%; min-width: 50%; } 
 <h2>Multiple items</h2> <div class="container"> <div class="item" style="background:tomato"></div> <div class="item" style="background:cyan"></div> </div> <h2>Single item</h2> <div class="container"> <div class="item" style="background:tomato"></div> </div> 

First of all you need to use the correct syntax for the flex style.

.item {
    flex: 1 1 auto;
}

It is easier to do this using position: relative on the items instead See this jsFiddle

If it is necessary to use position absolute then you would need to wrap the items in a wrapper and position that absolutely instead. See this jsFiddle

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