首页 > 解决方案 > div 与 html 单元格中的段落对齐

问题描述

我正在尝试创建一个表格,在每个单元格中,文本旁边都有一个彩色小方块。但是,我希望正方形和文本在同一行,但我做不到。

可悲的是,我不是 css 或 html 大师,我尝试了许多在此站点和其他站点上找到的对齐选项,但没有一个有效。您可以查看下面的最小示例来理解我在说什么。有没有办法在css中做到这一点?谢谢

.badge{
  background-color: #000000;
  width: 1em;
  height: 1em;
  border-radius: 25%;
}
<html>
  <body>
    <table border="1">
      <tr>
        <td>
          <div class="badge"></div> not horizontally aligned text
        </td>
      </tr>
    </table>
  </body>
</html>

标签: htmlcss

解决方案


<div>您可以为每个徽章创建一个::before伪元素,<td>并使其inline-block与文本内容保持内联,而不是为徽章嵌套 a 。这样,您可以确保每个表格数据元素在单元格文本内容之前都有一个小的彩色方块。

.badge::before {
  content: "";
  background-color: #000000;
  width: 1em;
  height: 1em;
  border-radius: 25%;
  display: inline-block;
  vertical-align: middle;
}

/* Optionally, give the cells different colors */
.badge.two::before {
  background-color: #ae7;
}

.badge.three::before {
  background-color: #f06;
}
<html>
  <body>
    <table border="1">
      <tr>
        <td class="badge one">
          some text in cell 1
        </td>
         <td class="badge two">
          some text in cell 2
        </td>
         <td class="badge three">
          some text in cell 3
        </td>
      </tr>
    </table>
  </body>
</html>

如果您想保持相同的 HTML 结构,您可以制作<td>一个flexboxdisplay: flex确保内容以行格式(并排)对齐。Usingalign-items将定义项目如何沿交叉轴对齐。

.badge{
  background-color: #000000;
  width: 1em;
  height: 1em;
  border-radius: 25%;
}

td {
  display: flex;
  align-items: center;
}
<html>
  <body>
    <table border="1">
      <tr>
        <td>
          <div class="badge"></div> not horizontally aligned text
        </td>
      </tr>
    </table>
  </body>
</html>


推荐阅读