Flex image won't shrink with screen size when container is a hyperlink

后端 未结 4 606
刺人心
刺人心 2021-01-23 10:31

Can someone let me know if this is an undocumented bug with flexbox, or that I\'m just doing it wrong? I\'ve got 3 images lined up in a row inside a div container. This is as si

4条回答
  •  广开言路
    2021-01-23 11:02

    The problem has nothing to do with hyperlinks. You could wrap the image in any element (try a span or a div) and it will have the same effect as the a container.

    The problem is the hierarchical structure of a flex container.

    When you set an element to display: flex (or inline-flex) you establish a flex container.

    Only the children of a flex container are flex items. Descendants of a flex container beyond the children are not flex items and don't accept flex properties.

    Here are the three flex items:

    The img in the first element is not a flex item. It is wrapped by the a element and is therefore a child of a flex item.

    The two img items can shrink because of two default settings on a flex container:

    1. flex-wrap: nowrap ~ flex items are forced to remain on a single line
    2. flex-shrink: 1 ~ flex items are permitted to shrink to prevent them from overflowing the container

    If you switch to flex-wrap: wrap and/or flex-shrink: 0 the img items will no longer shrink.

    The a item does not shrink because of another default setting: min-width: auto, which means that flex items cannot be smaller than the size of their content. In this case, the a item cannot shrink below the width of the image.

    You can override this setting by adding min-width: 0 to your code.

    #container {
      display: flex;
    }
    
    span {
      min-width: 0;
      display: flex;
    }
    
    img {
      min-width: 0;
    }

    More information:

    • Why don't flex items shrink past content size?
    • Proper use of flex properties when nesting flex containers

提交回复
热议问题