Placing a CSS grid layout inside a flexbox results in a broken layout only in mobile browsers

  Kiến thức lập trình

The problem is basically stated in the title, and it occurs only under these conditions:

  • parent element is display: flex; (or inline-flex), flex-direction: column;, and flex-wrap: wrap;
  • child element is display: grid;
  • not in PC browsers (Chrome, Firefox and Edge were all OK), but iPhone browsers (Safari, Chrome, Google App and Firefox)

I avoided using this element structure so this doesn’t bother me anymore, but I’m still curious if this is a bug or correct behavior.

If it’s not a bug, how can I fix my code to make it look the same on PC and mobile?

Thanks for your attention!

Here is my code.

I checked on Google Chrome, Firefox, Microsoft Edge (Windows 10 PC) / Safari, Google Chrome, Google (app), Firefox (iOS 16.7.7 iPhone 8).
It works as I expected in all browsers on PC, but in all browsers on iPhone, does not.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .flex {
            background-color: gray;
            width: 200px;
            display: flex; /* THIS */
            flex-direction: column; /* THIS */
            flex-wrap: wrap; /* THIS */
        }
        .grid {
            display: grid; /* THIS */
            outline: solid 1px red;
        }
        .child {
            outline: solid 1px lime;
            height: fit-content;
        }
    </style>
</head>
<body>
    <div class="flex">
        <div class="grid">
            <div class="child">A</div>
            <div class="child">A</div>
            <div class="child">A</div>
            <div class="child">A</div>
        </div>
    </div>
</body>

Screenshot: the left is PC, and the right is mobile appearance

New contributor

koh ymmt is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT