Using Flexbox to present 4 images in a ul as a 2x2 grid

前端 未结 1 389
借酒劲吻你
借酒劲吻你 2020-12-07 03:56

I am refactoring non-responsive code and am trying to display the below code as a 2x2 grid using Flexbox. I have tried using display:

相关标签:
1条回答
  • 2020-12-07 04:05

    HTML (no changes)

    CSS

    .gallery {}
    
    .gallery ul {
        display: flex;
        flex-flow: row wrap;
        list-style: none;
        margin: 32px 0;
    }
    
    .gallery li {
        margin: 0 10px;
        flex-basis: calc(50% - 20px);  /* width minus margins */
    }
    
    .gallery img {
        width: 100%;                   /* occupy 100% width of li container */
        height: auto;
    }
    

    DEMO

    NOTES:

    • When you create a flex container (by applying display: flex or display: inline-flex to an element), the child elements become flex items. The descendants of the flex container beyond the children do not become flex items and, therefore, do not accept flex properties.

      In your code, .gallery is the flex container. This means that its children – h2 and ul – are flex items. However, the children of the ul are not flex items and flex properties don't apply. That's why the images, contained in the li elements, "are acting as block elements and won't sit side by side".

    • To apply flex properties to the li elements, their parent must be made a flex container. By adding display: flex to the ul, the li's become flex items. (Note, the img elements remain inline elements because they are not children of the flex container.)

    0 讨论(0)
提交回复
热议问题