Home > OS >  Move central div to bottom on mobile
Move central div to bottom on mobile

Time:06-15

On desktop side columns will take a max-width of 175px leaving the center dynamic but on mobile I want to have a 2x1 grid. Also top columns will be 50% width but the height will depend on their content.

How could I move this center element to the bottom taking 100% of the width and leave the side columns next to each other taking each 50% of the width? I don't want to have hidden and duplicated elements.

#container {
  display: flex;
}

.column.left,
.column.right {
  max-width: 175px;
}

.column.center {
  flex: 1;
  text-align: center;
  background-color: red;
}

.column.left,
.column.right {
  text-align: center;
}
<body>
  <div id="container">
    <div >this is a long long long long label</div>
    <div >center</div>
    <div >short label</div>
  </div>
</body>

CodePudding user response:

You can use flex-wrap and the order property:

#container {
  display: flex;
}

.column.left,
.column.right {
  max-width: 175px;
}

.column.center {
  flex: 1;
  text-align: center;
  background-color: red;
}

.column.left,
.column.right {
  text-align: center;
}

@media all and (max-width: 600px) {
  #container {
    flex-wrap: wrap;
  }
  .column.left, .column.right {
    max-width: none;
    width: 50%;
  }
  .column.left {
    order: 1;
  }
  .column.right {
    order: 2;
  }
  .column.center {
    order: 3;
    width: 100%;
  }
}
<body>
  <div id="container">
    <div >this is a long long long long label</div>
    <div >center</div>
    <div >short label</div>
  </div>
</body>

CodePudding user response:

You can do this easily enough with CSS grid and a media query. See the snippet below

:root {
  --gridColTemplate: 1fr 1fr;
  --centerCol: 1/-1;
  --centerRow: 2;
  --sideMaxWidth: none;
}

#container {
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: var(--gridColTemplate);
}

.column { text-align: center }

.column.left, .column.right { max-width: var(--sideMaxWidth) }
.column.center {
  grid-column: var(--centerCol);
  grid-row: var(--centerRow);

  background-color: red;
}


@media only screen and (min-width: 600px) {
  :root {
    --gridColTemplate: auto 1fr auto;
    --centerCol: 2/3;
    --centerRow: 1;
    --sideMaxWidth: 175px;
  }
}
<div id="container">
  <div >this is a long long long long label</div>
  <div >center</div>
  <div >short label</div>
</div>

  • Related