将项目与Flexbox显示在块内对齐

时间:2018-08-13 08:22:52

标签: css flexbox

我正在使用flexbox显示列表(ul li)

下面有一个codepen或代码段,用于显示我的代码和问题。

body {
  font-family: Arial;
  font-size: small;
}

h1 {
  font-size: small;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: rgba(0, 0, 255, .5);
  font-size: 12px;
}

li {
  width: 200px;
  padding: 1em;
  background-color: rgba(255, 0, 0, .5);
}

.ul-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
<h1>Standard code</h1>
<div>
  <ul class="ul-container">
    <li>
      <div class="description">
        <h2>Block 1</h2>
        <p>Text 1<br/>Text 1</p>
        <p>Text 2</p>
        <p>Text 3</p>
      </div>
    </li>
    <li>
      <div class="description">
        <h2>Block 2</h2>
        <p>Text 1</p>
        <p>Text 2<br/>Text 2</p>
        <p>Text 3</p>
      </div>
    </li>

    <li>
      <div class="description">
        <h2>Block 3</h2>
        <p>Text 1</p>
        <p>Text 2</p>
        <p>Text 3</p>
      </div>
    </li>
  </ul>
</div>

<h1>Expected result</h1>
<p> 'br' have been forced to demonstrate the expected behaviour ('Text1 - block 1' and 'Text2 - block 2' have 2 lines)
  <div>
    <ul class="ul-container">
      <li>
        <div class="description">
          <h2>Block 1</h2>
          <p>Text 1<br/>Text 1</p>
          <p>Text 2<br/>&nbsp;</p>
          <p>Text 3</p>
        </div>
      </li>
      <li>
        <div class="description">
          <h2>Block 2</h2>
          <p>Text 1<br/>&nbsp;</p>
          <p>Text 2<br/>Text 2</p>
          <p>Text 3</p>
        </div>
      </li>

      <li>
        <div class="description">
          <h2>Block 3</h2>
          <p>Text 1<br/>&nbsp;</p>
          <p>Text 2<br/>&nbsp;</p>
          <p>Text 3</p>
        </div>
      </li>
    </ul>
  </div>
  <p>Or ('Text2 - Block 2' have 2 lines)</p>
  <div>
    <ul class="ul-container">
      <li>
        <div class="description">
          <h2>Block 1</h2>
          <p>Text 1</p>
          <p>Text 2<br/>&nbsp;</p>
          <p>Text 3</p>
        </div>
      </li>
      <li>
        <div class="description">
          <h2>Block 2</h2>
          <p>Text 1</p>
          <p>Text 2<br/>Text 2</p>
          <p>Text 3</p>
        </div>
      </li>

      <li>
        <div class="description">
          <h2>Block 3</h2>
          <p>Text 1</p>
          <p>Text 2<br/>&nbsp;</p>
          <p>Text 3</p>
        </div>
      </li>
    </ul>
  </div>

我想根据内容(每个段落的大小和大小)动态地调整列表项中的段落,有没有办法用纯CSS来实现?

谢谢

Expected behaviour

1 个答案:

答案 0 :(得分:-1)

您正在尝试使用display: felxbox来创建网格。只需使用display: grid,您将获得预期的结果。

一般规则是:

  • flexbox用于对齐项目和灵活的布局
  • grid用于一致的二维(网格)布局

您可以找到如何here的好方法。