【问题标题】:Divs with same class adjust to different content具有相同类的 div 适应不同的内容
【发布时间】:2017-10-05 16:22:19
【问题描述】:

我有三个相邻的 div。它们具有相同的类和相同的结构,但它们的内容不同,特别是在长度上。 我的问题是,所有三个 div 都采用具有“最长”内容的那个的高度,而不是根据各自的内容进行调整。

这是我的 HTML:

<main class="content">
 <div class="column last-match">                    
  <div class="image-wrapper">
   <a href="#"><img src="default_thumbnail.jpg"/></a>
  </div>
  <div class="text-wrapper">
   <a class="heading" href="#"><p class="heading">A Heading</p></a>
   <p class="post-excerpt">Some text</p>
   <a href="#" class="button read-more">Read More</a>
  </div>
 </div>
 <div class="column last-match">                    
  <div class="image-wrapper">
   <a href="#"><img src="default_thumbnail.jpg"/></a>
  </div>
  <div class="text-wrapper">
   <a class="heading" href="#"><p class="heading">A Heading</p></a>
   <p class="post-excerpt">Some text that's longer</p>
   <a href="#" class="button read-more">Read More</a>
  </div>
 </div>
 <div class="column next-matches">
  <div class="image-wrapper">
   <img src="next_matches.jpg"/>
  </div>
  <div class="text-wrapper">
   <p class="heading">List Heading</p>
   <ul class="match-list">
    <li class="match">some list item</li>
    <li class="match">some list item</li>
   </ul>
  </div>
 </div> 
</main>

还有基本的 CSS:

.content {
    display: flex;
    flex-wrap: nowrap;
}

.column {
    display: flex;
    flex-direction: column;
    margin: 60px 20px;
    min-height: 100px;
    width: 33%;
}

.image-wrapper {
    width: 100%;
    height: 260px;
    overflow: hidden;
}

.image-wrapper img {
    width: 100%;
    height: auto;
}

.post-excerpt {
    margin-bottom: 20px;
}

.button {
    display: block;
    float: left;
    margin-bottom: 20px;
    padding: 10px;
}

.match {
    font-size: 1em;
    padding-top: 15px;
}

这是我在 JSFiddle 上的代码:https://jsfiddle.net/4h0g73sp/5/

如您所见,列将采用其中包含最多文本的列的高度。我想要的是它们根据内容进行调整,以便在必要时具有不同的高度。

我不知道是否值得注意,我正在使用 Wordpress,所以这些列最初是在一些 php.ini 中。如果这很重要,我很乐意与您分享代码,所以请告诉我:)

【问题讨论】:

标签: html css flexbox


【解决方案1】:

问题是因为弹性容器上的align-items 默认为stretch,所以弹性项目采用最高项目的高度(行)。

只需将其设置为flex-start

.content {
    display: flex;
    align-items: flex-start;
}

https://jsfiddle.net/4h0g73sp/9/

我还从.content 中删除了flex-wrap,因为默认是不换行,所以不需要声明它

检查https://css-tricks.com/snippets/css/a-guide-to-flexbox/ 它非常有用,并且很好地演示了 flex

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2019-01-15
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多