首页 > 解决方案 > 如何使用 flexbox 将三个相邻的 p 元素均匀排列

问题描述

我正在制作三个并排的盒子。每个框都有一个图像+标题+文本。第一个框包含一个带有两个单词的标题。缩小浏览器时,框 2 和框 3 的 p 内容排列得比框 1 高。

我使用的代码是:

<section id="boxes">
    <div class="container">
        <div class="box">
            <img src="https://www.w3.org/html/logo/downloads/HTML5_1Color_Black.png" alt="html5 logo">
            <h3>HTML 5 Website</h3>
            <p>Curabitur porttitor metus odio, fringilla bibendum sem faucibus quis. C</p>
        </div>
        <div class="box">
            <img src="https://www.w3.org/html/logo/downloads/HTML5_1Color_Black.png" alt="html5 logo">
            <h3>Webbie</h3>
            <p>Curabitur porttitor metus odio, fringilla bibendum sem faucibus quis. C</p>
        </div>
        <div class="box">
            <img src="https://www.w3.org/html/logo/downloads/HTML5_1Color_Black.png" alt="html5 logo">
            <h3>Informatie</h3>
            <p>Curabitur porttitor metus odio, fringilla bibendum sem faucibus quis. C</p>
        </div>
    </div>
</section>

和CSS:

#boxes .container {
    display: flex;
    max-width: 900px;
}

.box {
    display: flex;
    flex-direction: column;
}


.box img {
    /*prevents image from being larger than it's container, but doesn't stretch it if it's smaller than the container*/
    /*if you had a 20x20px image, then it would not get stretched to match the container's width, but it would stay 20x20px. Whereas a 2000x2000px image would get scaled down to fit the container*/
    max-width: 100%;
}

jsfiddle: https ://jsbin.com/gudomuyora/edit?html,css,output

如何将 3 个框中的 p 个元素的顶部均匀排列。

标签: htmlcss

解决方案


您可以使用justify-content: space-betweenon.box来实现这一点。

#boxes .container {
  display: flex;
  max-width: 900px;
}

.box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.box img {
  max-width: 100%;
  flex: 0 0 auto;
}

.box h3 {
  flex: 1 1 auto;
}

.box p {
  flex: 0 1 auto;
}
<section id="boxes">
  <div class="container">
    <div class="box">
      <img src="https://www.w3.org/html/logo/downloads/HTML5_1Color_Black.png" alt="html5 logo">
      <h3>HTML 5 Website</h3>
      <p>Curabitur porttitor metus odio, fringilla bibendum sem faucibus quis. C</p>
    </div>
    <div class="box">
      <img src="https://www.w3.org/html/logo/downloads/HTML5_1Color_Black.png" alt="html5 logo">
      <h3>Webbie</h3>
      <p>Curabitur porttitor metus odio, fringilla bibendum sem faucibus quis. C</p>
    </div>
    <div class="box">
      <img src="https://www.w3.org/html/logo/downloads/HTML5_1Color_Black.png" alt="html5 logo">
      <h3>Informatie</h3>
      <p>Curabitur porttitor metus odio, fringilla bibendum sem faucibus quis. C</p>
    </div>
  </div>
</section>


推荐阅读