panthro
panthro

Reputation: 24059

Flex- change position of child's child?

I wish to get A to sit at the top, B to sit in the middle and C to sit at the bottom.

JSFiddle

<div class="container">
    <div class="a">A</div>
    <div class="sub-container">
        <div class="b">B</div>
        <div class="c">C</div>
    </div>
</div>

CSS:

.container{
    display: flex; 
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
    position: fixed;
}

i need to keep the same markup - how can I change the position of a div that is not the immediate child of the flex container?

EDIT:

It should look like this

A

B

C

Upvotes: 0

Views: 1495

Answers (2)

FelipeAls
FelipeAls

Reputation: 22171

With this HTML code where .b and .c aren't siblings of .a, you can achieve desired result with a flex inception: .sub-container is both a flex item of parent .container and a flex container for .b and .c

flex: 2 0 auto; is related to height ratio of 1/3 + (1/3 + 1/3)

Fiddle

.container{
display: flex; 
flex-direction: column;
justify-content: space-between;
width: 100%;
height: 100%;
position: fixed;
}
.sub-container {
flex: 2 0 auto;
/* flex inception */
display: flex;
flex-direction: column;
background-color: lightgreen;
}
.a, .b, .c {
flex: 1 0 auto; /* .a and .b, .c are not flex items of the same parent though we still want the same value */
padding: 1rem 0;
text-align: center;
}
<div class="container" style="background-color: blue;">
  <div class="a" style="background-color: red;">A</div>
  <div class="sub-container" style="background-color: green;">
    <div class="b">B</div>
    <div class="c">C</div>
  </div>
</div>

Upvotes: 0

Oriol
Oriol

Reputation: 288220

The CSS Display Module Level 3 introduces display: contents:

The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced with its children and pseudo-elements in the document tree.

You can use it to "ignore" the subcontainer, and display all the inner items as if they belonged to the same container.

body { margin: 0 }
.container {
  display: flex; 
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  position: fixed;
}
.sub-container {
  display: contents;
}
<div class="container">
  <div class="a">A</div>
  <div class="sub-container">
    <div class="b">B</div>
    <div class="c">C</div>
  </div>
</div>

It's not widely supported yet, though.

Upvotes: 2

Related Questions