假设我有这样一段文本:
x = 2 / y
a + b + c = x
通过CSS(或其他技巧)是否有可能使这些行对齐,以达到以下效果?
x = 2 / y
a + b + c = x
我想我可以将等式左边放在第一列,等号放在第二列,右边的部分放在第三列,然后使用右对齐,居中和左对齐来排版。但这种方式并不感觉干净或语义正确 :p。
text-align
来对齐文本。white-space
来保留空格,并结合等宽字体使用,Fiddle: http://jsfiddle.net/cCLZy/
<style>
.right-align {
/*text-align: right;*/
white-space: pre;
font-family: monospace;
}
</style>
<!-- Spaces and newlines are preserved -->
<div class="right-align">
x = 2
a + b + c = x
</div>
可能有点严格,但我希望这可以帮到你。
关键在于 display: table-cell
属性,以及给 <span>
标签一个“固定”的宽度。
例如,我给 <span>
标签设置了 width:6em
,这适用于较短的句子,如下面的代码片段或 这里 的演示。
body{ font-family:consolas, courier, monospaced }
div>span:nth-of-type(1){ text-align:right }
div>span:nth-of-type(3){ text-align:left }
div>span.equal:after{ content:'=' }
div>span{ display:table-cell; width:6em }
div>span.equal{ background:pink; width:1em; padding-left:0.5em }
<div>
<span>x</span>
<span class="equal"></span>
<span> 2 / y</span>
</div>
<div>
<span>a + b + c</span>
<span class="equal"></span>
<span>x</span>
</div>
<div>
<span>x + y</span>
<span class="equal"></span>
<span>a + b + c</span>
</div>
但在特定情况下,比如对齐数学公式,使用专门用于呈现数学的工具(如LaTeX)可能会更容易。在LaTeX中对齐方程非常简单和灵活。要将LaTeX添加到浏览器中,您可以使用JS库,例如MathJax或KATEX。
你总是把文本放在表格中,这样可以让一切对齐。
我没有测试过这种方法,可能需要一些调整,但应该可以工作。如果您想对齐等号,可以这样做:
<style>
.left {
width: x; /*You have to give them width to make the effect of two columns*/
text-align: right;
float: left;
}
.right {
width: x; /*You have to give them width to make the effect of two columns*/
text-align: left;
float: left;
}
.clr { clear: both; } /*Clear to keep next elements from floating too*/
</style>
<div class="left">
<p>x = <br />
a + b + c =</p>
</div>
<div class="right">
<p>2 / y<br />
x</p>
</div>
<div class="clr"></div>
text-align:right
??