I'm trying to format the pre
element to follow these two behaviors, but can't figure out how to do it:
pre
element is less than the set width of its container, then horizontally align it with respect to its container.pre
element is greater than the set width of its container, then set the pre
element's overflow-x
to scroll such that the scroll is on the pre element itself and not on the container.The following below:
pre
element.body {
background: cyan;
}
.c1, .c3 {
text-align: center;
}
pre[class^='case'] {
background: lightgreen;
}
.case1 {
text-align: initial;
display: inline-block;
}
.case2 {
overflow-x: scroll;
}
.case3 {
text-align: initial;
display: inline-block;
overflow-x: scroll;
}
<div class='c1'>
<pre class='case1'>
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
</pre>
</div>
<div class='c2'>
<pre class='case2'>
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1 testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest
</pre>
</div>
<div class='c3'>
<pre class='case3'>
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1 testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest
</pre>
</div>
As an alternative, if it is possible to horizontally center the contents of the pre
element, this would work too.
答案 0 :(得分:1)
这应该可以解决问题:
pre {
display: inline-block;
text-align: initial;
max-width: 100%;
overflow-x: auto;
}
应用于您的代码段:
body {
background: cyan;
}
.c1, .c3 {
text-align: center;
}
pre[class^='case'] {
background: lightgreen;
}
pre {
display: inline-block;
text-align: initial;
max-width: 100%;
overflow-x: auto;
}
&#13;
<div class='c1'>
<pre class='case1'>
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
</pre>
</div>
<div class='c2'>
<pre class='case2'>
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1 testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest
</pre>
</div>
<div class='c3'>
<pre class='case3'>
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1 testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest
</pre>
</div>
&#13;