如何在<pre> appear only when text overflows?

时间:2017-11-13 06:05:50

标签: html css

I have a certain number of <pre> tags in my page, as shown. I'd like the horizontal scrollbars to appear only there are long lines of text in the tag.

Here is my attempt to do so:

pre {
  background-color: #d0d0d0;
  overflow-x: scroll;
  margin: 3px 0;
  text-align: left;
}

main {
  max-width: 300px;
  margin: 0 auto;
}
<main>
Set up the master:
<pre># ./setup.sh --master
</pre>

Set up the slaves:
<pre># ./setup.sh --slave --master-ip=10.0.2.2 --port=5670</pre>
</main>

However, the scrollbars are displayed even for <pre> tags where there is no overflow. How can I do so?

1 个答案:

答案 0 :(得分:2)

Give overflow-x: auto; instead of overflow-x: scroll;.

pre {
  background-color: #d0d0d0;
  overflow-x: auto;
  margin: 3px 0;
  text-align: left;
}

main {
  max-width: 300px;
  margin: 0 auto;
}
<main>
  Set up the master:
  <pre># ./setup.sh --master
  </pre>

  Set up the slaves:
  <pre># ./setup.sh --slave --master-ip=10.0.2.2 --port=5670</pre>
</main>