有没有办法用 CSS 对齐浮动 HTML 元素?
本质上,我试图通过浮动块元素来实现“text-align:justify”的效果。我有很多块想要对齐。
IE。每条线的水平间距不同,以确保每条线的长度相同。 (右边缘无锯齿)。
有没有办法用 CSS 做到这一点?如果没有,是否有合适的JS库来实现这一点?或者这根本不可行?
Essentially, I'm trying to achieve the affect of "text-align:justify" but with floating block elements. I have many blocks that I want to justify-align.
Ie. each line is horizontally-spaced differently to make sure lengths of each line are the same. (Non-ragged right edge).
Is there a way to do this with CSS? If not, is there a suitable JS library to achieve this? Or is this just infeasible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果项目实际上不是浮动的,您可以使用position:absolute;左:1em; right:1em 让 CSS 根据距某个定位父级的偏移量计算项目的宽度。
如果您仅使用
float
因为您有一些块级项目想要使其流动,请在这些项目上使用display:inline-block
而不是浮动它们。如果父元素有text-align:justify
这应该会给你你想要的效果(我想是这样)。这是一个 简单测试,向您展示
inline-block
的结果 <代码>文本对齐:对齐。编辑:我更新了简单的测试,以更清楚地显示除了最后一行之外,左右边缘始终对齐。
If the items are not actually
float
ing, you can useposition:absolute; left:1em; right:1em
to have CSS calculate the widths of the items for you based on offsets from some positioned parent.If you are only using
float
because you have some block-level items you are trying to make flow, usedisplay:inline-block
on the items instead of floating them. If the parent element hastext-align:justify
this should give you the effect (I imagine that) you want.Here is a simple test showing you the result of
inline-block
withtext-align:justify
.Edit: I've updated the simple test to more clearly show that the left and right edges are always aligned except for the last line.
完成前面的答案后,如果您想对齐以编程方式创建的 DOM 节点(例如,通过在 javaScript 中使用 document.createElement 和parentElement.appendChild),则对齐的元素之间不会添加空格。这可能会导致对准不起作用。
在我的 Google Chrome 56.0.2924.87 和 Firefox 51.0.1(64 位)浏览器上,如果没有任何空格来分隔
div
元素,则对齐不起作用:https://jsfiddle.net/jc5qwyaw/
我通过javaScript创建DOM节点时有一个例子:
https://jsfiddle.net/oa8yeudr/
如果取消注释命令
wrapDiv.appendChild(document.createTextNode(" "));
,你可以看到区别。可能的解决方案可以是在 div 节点后面附加一个空白文本节点,如上面的示例所示。
仅在 Chrome 56.0.2924.87 和 Firefox 51.0.1(64 位)上进行了测试。
Completing previous answer, if you want to align DOM nodes created programatically (e.g. by using document.createElement and parentElement.appendChild in javaScript), no white space will be added between aligned elements. This can cause non-working of aligment.
On my Google Chrome 56.0.2924.87 and Firefox 51.0.1 (64-bit) browsers, aligment doesn't work if there aren't any white spaces to separate
div
elements:https://jsfiddle.net/jc5qwyaw/
There is an example when I create DOM nodes by javaScript:
https://jsfiddle.net/oa8yeudr/
If you uncomment command
wrapDiv.appendChild(document.createTextNode(" "));
, you can see the difference.Possible solution can be appending a white space text node after div nodes as example shows above.
Only tested on Chrome 56.0.2924.87 and Firefox 51.0.1 (64-bit).