Ronit Mukherjee
Ronit Mukherjee

Reputation: 405

Align multiple stacked items vertically at different positions using CSS

I have tried using CSS Grid and CSS Flex to achieve it, but can't achieve it completely.

Requirement:

I have a container inside which I have multiple items, each item has a configuration of top, centre and bottom as vertical alignments. All the top items should appear at the top, all centre items at the centre and all bottom items at the bottom of the parent.

The items are dynamic means there can be any number of the item and each item can have any position(Top, Centre, Bottom).

The only restriction given to the user is that they will add the items in order means 1st he will add top items, then centre items and then bottom items.

enter image description here

<div class="parent">
    <div class="child top"> Item 1</div>
    <div class="child top"> Item 2</div>
    <div class="child center"> Item 3</div>
    <div class="child center">Item 4</div>
    <div class="child bottom"> Item 5</div>
    <div class="child bottom"> Item 6</div>
  </div>
</div>

Upvotes: 3

Views: 274

Answers (1)

Temani Afif
Temani Afif

Reputation: 274374

You can do this using order and pseudo elements. The trick is that both pseudo elements will be between the top/center and bottom/center and will fill all the space. You can also have the element scrambled, the HTML order doesn't matter:

.parent {
  height:500px;
  border:2px solid;
  display:flex;
  flex-direction:column;
}
.parent > * {
  padding:10px;
  background:red;
  color:#fff;
  text-align:center;
}

.top { order:1}
.parent:before {
  content:"";
  order:2;
  flex:1
}
.center { order:3}
.parent:after {
  content:"";
  order:4;
  flex:1
}
.bottom { order:5}
<div class="parent">
    <div class="child center"> Item 3</div>
    <div class="child top"> Item 1</div>
    <div class="child center">Item 4</div>
    <div class="child bottom"> Item 5</div>
    <div class="child bottom"> Item 6</div>
    <div class="child top"> Item 2</div>
    <div class="child bottom"> Item 7</div>
    <div class="child top"> Item 8</div>
</div>

Another idea since you said that the order will be respected is to consider the + selector and auto margin:

.parent {
  height:500px;
  border:2px solid;
  display:flex;
  flex-direction:column;
}
.parent > * {
  padding:10px;
  background:red;
  color:#fff;
  text-align:center;
}

.top + .center {
  margin-top:auto;
}

.center + .bottom {
  margin-top:auto;
}
<div class="parent">
    <div class="child top"> Item 1</div>
    <div class="child top"> Item 2</div>
    <div class="child center"> Item 3</div>
    <div class="child center">Item 4</div>
    <div class="child bottom"> Item 5</div>
    <div class="child bottom"> Item 6</div>
</div>

Upvotes: 2

Related Questions