代码之家  ›  专栏  ›  技术社区  ›  alan

有没有办法向flexbox图像添加链接?

  •  0
  • alan  · 技术社区  · 3 年前

    这适用于(没有链接的图像):

    <div id="gallery">
         <img src="1.jpg"/>
         <img src="2.jpg"/>
         <img src="3.jpg"/>
         <img src="4.jpg"/>
    </div>
    
     #gallery {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        padding: 0 4px;
      }
      
      #gallery img {
        width: 25%;
        height: 300px;
        object-fit: cover;
        margin-top: 8px;
        padding: 0 4px;
        border-radius: 10px;
      }
    

    这完全把事情搞砸了。css(带链接的图像):

    <div id="gallery">
         <a href="1.jpg"><img src="1.jpg"/></a>
         <a href="2.jpg"><img src="2.jpg"/></a>
         <a href="3.jpg"><img src="3.jpg"/></a>
         <a href="4.jpg"><img src="4.jpg"/></a>
    </div>
    

    唯一能让它变得更好的是添加:

    #gallery a {
        width: 100%;
    }
    

    但这只是一个垂直的图像堆栈。
    那么flexbox是否不允许将图像作为链接?

    2 回复  |  直到 3 年前
        1
  •  2
  •   dippas    3 年前

    您需要从中重新应用样式 img a 因为flexbox仅适用于直接子级

    #gallery {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
      padding: 0 4px;
    }
    
    #gallery a {
      width: 25%;
      height: 300px;
      margin-top: 8px;
      padding: 0 4px;
      box-sizing: border-box;
    }
    
    #gallery img {
      border-radius: 10px;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    <div id="gallery">
      <a href="1.jpg"><img src="https://picsum.photos/200/300?random=1" /></a>
      <a href="2.jpg"><img src="https://picsum.photos/200/300?random=2" /></a>
      <a href="3.jpg"><img src="https://picsum.photos/200/300?random=3" /></a>
      <a href="4.jpg"><img src="https://picsum.photos/200/300?random=4" /></a>
    </div>