Home > Back-end >  CSS Flexbox and Grid: is the order's default value 0 or 1?
CSS Flexbox and Grid: is the order's default value 0 or 1?

Time:06-01

In Flexbox and Grid, we can change the order in which items are displayed, with among other things the order property. Everywhere, I'm reading that the default order value is 0, also on https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items.

But look at this example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Order demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
<style>
    body {
        margin: 40px;
    }
    .wrapper {
        width: 600px;
        display: grid;
        grid-template-columns: repeat(6, 100px);
        grid-gap: 10px;
    }
    .box {
        background-color: #444;
        color: #fff;
        border-radius: 5px;
        padding: 20px;
        font-size: 150%;
        order: 1;
    }
    .box:nth-child(even) {
        background-color: #ccc;
        color: #000;
    }
    .box2 {
        order: 0;
    }
</style>
</head>
<body>
    <div >
        <div >1</div>
        <div >2</div>
        <div >3</div>
        <div >4</div>
        <div >5</div>
        <div >6</div>
        <div >7</div>
        <div >8</div>
        <div >9</div>
        <div >10</div>
        <div >11</div>
        <div >12</div>
    </div>
</body>
</html>

Here is the corresponding Pen, in which you can see the rendering: https://codepen.io/FrankConijn/pen/BaYxBzd.

Item nr. 2 is displayed first, while it has order: 0, which should have it displayed in the order in which it is placed in the code (2nd). That suggests that the specs are incorrect, and that the default value is 1. Am I right?

CodePudding user response:

order does indeed have a default value of 0 (MDN formal definition & MDN 'Ordering Flex Items'), but in your example you've overridden this by giving each .box an explicit order: 1; here the order: 0 on .box2 is behaving correctly according to its property in appearing in the 1st position.

If you remove the order on your .box class and let them order by default (0) you'll see that the position of .box2 is placed as it should be: as the 2nd box:

body {
  margin: 40px;
}

.wrapper {
  width: 600px;
  display: grid;
  grid-template-columns: repeat(6, 100px);
  grid-gap: 10px;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}

.box:nth-child(even) {
  background-color: #ccc;
  color: #000;
}

.box2 {
  order: 0;
}
<body>
  <div >
    <div >1</div>
    <div >2</div>
    <div >3</div>
    <div >4</div>
    <div >5</div>
    <div >6</div>
    <div >7</div>
    <div >8</div>
    <div >9</div>
    <div >10</div>
    <div >11</div>
    <div >12</div>
  </div>
</body>

  • Related