RomeNYRR
RomeNYRR

Reputation: 887

Antd Responsive Flex for Columns

I've implemented antd in my react project and there's one thing that I can't figure out for the life of me. I have a row with 3 columns and when the screen size shrinks, I want to collapse the 3 columns into a single column.

Whenever I resize the screen they just collapse one at a time instead of all at once. I was able to get this going in vanilla html/css using flex, but for some reason I can't get the same effect with antd. I've tried adding media query, but no luck.

Here's what it looks like when it starts to collapse, and I've also attached my codepens for reference. Could it be that my flex settings on the columns are set incorrectly?

Unexpected Collapsing

React Example: Codepen

CSS

@import 'antd/dist/antd.css';

.Red {background: red; color: white; width: 200px;}
.Green {background: green; color: white; width: 200px;}
.Blue {background: blue; color: white; width: 200px;}

@media screen and (max-width: 992px) {
  .column {
    flex: 10%;
  }
}

JS

const {  Row, Col, Divider  } = antd;

ReactDOM.render(
  <>
    <Row className="row">
      <Col flex="1 0 auto" className="column Red">Red</Col>
      <Col flex="1 0 auto" className="column Green">Green</Col>
      <Col flex="1 0 auto" className="column Blue">Blue</Col>
    </Row>
  </>,
  mountNode,
);

Vanilla Example: (Expected output): Codepen

HTML

<div class="row">
  <div class="column red">Red</div>
  <div class="column green">Green</div>
  <div class="column blue">Blue</div>
</div>

CSS

.red {background: red; color: white; width: 300px; float: left}
.green {background: green; color: white; width: 300px; float: left}
.blue {background: blue; color: white; width: 300px; float: left}

/* Container for flexboxes */
.row {
  display: flex;
  flex-wrap: wrap;
}

.column {
  flex: 25%;
  padding: 20px;
}

@media screen and (max-width: 800px) {
  .column {
    flex: 50%;
  }
}

Upvotes: 6

Views: 27795

Answers (1)

m4n0
m4n0

Reputation: 32255

The flex-basis that you set to auto makes the wrapping behavior to split into two columns before splitting it into three. Because it is the minimal initial value set like width for a row and height for a column.

You can set the flex-basis to 25% so that it does not split according to default wrapping behaviour.

Changes made -

HTML

const {  Row, Col, Divider  } = antd;

ReactDOM.render(
  <>
    <Row className="row">
      <Col flex="1 0 25%" className="column Red">Red</Col> <!-- From auto to 25%, same as below -->
      <Col flex="1 0 25%" className="column Green">Green</Col>
      <Col flex="1 0 25%" className="column Blue">Blue</Col>
    </Row>
  </>,
  mountNode,
);

CSS

@media screen and (max-width: 992px) {
  .column {
    flex: 100% !important; /* !important so that it overrides the inline style because by default it has higher priority */
  }
}

Codepen Demo: https://codepen.io/m4n0/pen/OJNrLqz

3 columns split

Upvotes: 9

Related Questions