0

html {
    padding: 0;
    margin: 0;
    background-color: red;
}

body {
    padding: 1em;
    width: 50em;
    background-color: azure;
    margin-left: auto;
    margin-right: auto;
}
@media screen and (max-width: 50em) {
    body {
        width: 100%;
    }
}

ul {
    padding: 0;
    display: flex;
    justify-content: space-evenly;
    flex-wrap: wrap;
}

ul>li {
    /* flex-basis: 25%; */
    min-width: 25%;
    margin: 1em;
    list-style: none;
    background-color: greenyellow;
    justify-content: center;
}

ul>li>a {
    margin: 0 auto;
    padding: 0;
    display: block;
    background-color: lightgrey;
    width: 10em;
    height: 10em;
}
<html>
  <body>
    <ul>
      <li>
        <a href="#">1</a>
      </li>
      <li>
        <a href="#">2</a>
      </li>
      <li>
        <a href="#">3</a>
      </li>
      <li>
        <a href="#">4</a>
      </li>
      <li>
        <a href="#">5</a>
      </li>
      <li>
        <a href="#">6</a>
      </li>
    </ul>
  </body>
</html>

Sorry if my example is not minimal, but I don't know were the issue is exactly. My aim is to have a simple responsive page:

  • If my screen width is > 50em, the body is limited to 50 em.
  • Otherwise it takes all the width (100%).

In this body, I want to have 6 flex elements, so that there can never be more than 3 elements per line. Concretely, that means that the only valid patterns are 3x2, 2x3, 1x6.

All is correct, as long as I don't add a padding to the body. As soon as I add a padding, the flex makes the page width to exceed the screen size.

Why is that? How can I simply achieve what I want?

Boiethios
  • 25,767
  • 8
  • 91
  • 135

1 Answers1

3

Just add box-sizing: border-box to all elements, which will include the padding (and borders) in all width/height calculations instead of adding it. (and thereby not break calculations like yours)

* {
  box-sizing: border-box;
}
Johannes
  • 53,485
  • 15
  • 52
  • 104
  • Hum, it solves my snippet, but not my real code. Not sure why, I'm investigating. Thanks for this hint, tho. – Boiethios Jul 29 '19 at 11:19