如何使用flexbox将三个p元素均匀地排列在一起

时间:2018-11-02 14:45:21

标签: html css

我要使三个盒子彼此相邻。每个框都有一个图像+标头+文本。 第一个框包含带有两个单词的标题。缩小浏览器时,框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: {{3}}

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

1 个答案:

答案 0 :(得分:2)

您可以在justify-content: space-between上使用.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>