html - 在同一个列表元素中左右对齐文本

标签 html css

我想要一个列表元素,其中一个文本左对齐,另一个文本右对齐。

我试过这个:https://jsfiddle.net/dso5x75g , 但它没有像我预期的那样工作,因为“点”在文本上。

我怎样才能正确地做到这一点?

我的代码:

<ul>
    <li>
        <div style="float:left;">Pizza </div>
        <div style="float:right;">€ 20,00</div>
    </li>
 </ul>

最佳答案

您忘记清除默认的 ul 样式。添加以下 CSS:

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

因为你正在使用 float 所以也设置 li 的布局:

ul li {
  overflow: hidden;
}

或者使用:after伪元素:

ul li:after {
  display: block;
  content: '';
  clear: both;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

ul li {
  overflow: hidden;
}
<ul>
  <li>
    <div style="float:left;">Pizza </div>
    <div style="float:right;">€ 20,00</div>
  </li>
</ul>

除了使用 float ,您还可以使用 css3 flexbox在两个方向对齐文本。您将需要以下 CSS:

ul li {
    justify-content: space-between;
    display: flex;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
ul li {
  justify-content: space-between;
  display: flex;
}
<ul>
  <li>
    <div>Pizza </div>
    <div>€ 20,00</div>
  </li>
</ul>

如果目标是使用自定义图像作为元素符号,您可以使用 :before 伪元素绘制它们:

ul {
  list-style: none;
  padding: 0 20px;
  margin: 0;
}
ul li {
  position: relative;
  overflow: hidden;
  padding-left: 15px;
}

ul li:before {
  background-color: black;
  position: absolute;
  height: 5px;
  content: '';
  width: 5px;
  left: 0;
  top: 5px;
}
<ul>
  <li>
    <div style="float:left;">Pizza </div>
    <div style="float:right;">€ 20,00</div>
  </li>
</ul>

在上面的代码片段中,您可以将 background-color 更改为 background-image 并设置 widthheight 因此。这将使您能够完全控制图像的位置以及图像和文本之间的缩进。

关于html - 在同一个列表元素中左右对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40805650/

相关文章:

html - 我无法将我的 <twittercontainer> div 对齐到 <srun> 和 <mentor> 的右侧;我似乎也无法控制推特嵌入的高度

html - 复选框垂直对齐

html - 固定标题溢出父容器

javascript - 展开 div 到 "read more"

html - Div 显示为表格 inside div 显示为表格

javascript - Bootstrap 按钮大小随着浏览器大小的减小而最终变为 xs

php - Wordpress:从图库中隐藏特色图片缩略图

javascript - 使用 backbone 时 css 不工作

html - 为什么我的页脚中的图像没有留在容器内?

php - 检查 MySQL 数据库并添加代码 PHP