我想要一个列表元素,其中一个文本左对齐,另一个文本右对齐。
我试过这个: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
并设置 width
和 height
因此。这将使您能够完全控制图像的位置以及图像和文本之间的缩进。
关于html - 在同一个列表元素中左右对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40805650/