如何制作具有定义宽度的代码块?

问题描述 投票:0回答:2

我正在尝试将代码块添加到我正在制作的文档网站中,但是我无法使代码块具有定义的宽度。其宽度仅与其中的文字相关。

我希望代码块具有固定的宽度,并且文本只是放在其中,而不是使代码块受文本大小的限制。

* {
  width: 1265px;
  font-family: 'Roboto', sans-serif;
}

body {
  display: inline-block;
}

main {
  margin: auto;
}

.centerContent {
  width: 75%;
  margin: auto;
  float: right;
}

.sidebar {
  width: 25%;
  margin-top: 10px;
  float: left;
}

.clearfix::after {
  content: "";
  clear: both;
  display: table;
}

code {
  width: 600px;
  font-family: 'Source Code Pro', monospace;
  color: #43892a;
  background-color: #000;
}
<header>
  <h1>Batch Documentation</h1>
</header>
<main class="clearfix">
  <div class="sidebar">
    <ul>
      <li>Test</li>
      <li>Test2</li>
      <li>Test3</li>
    </ul>
  </div>
  <div class="centerContent">
    <h2>Sample text</h2>
    <code>Hello</code>
  </div>
</main>

足够有趣:我希望代码块看起来像本网站中的代码块。不是在谈论颜色,而是在谈论它们的大小。

html css width inline styling
2个回答
2
投票

HTML中的<code>元素默认为内联元素,并且您无法为内联元素定义widthheight

这里的解决方案就像添加一样简单

display: block

在元素CSS中显示以下结果

code {
  width: 600px;
  font-family: 'Source Code Pro', monospace;
  color: #43892a;
  background-color: #000;
  display: block;
}

有关内联和宽度的更多信息,您可以阅读this question

[此外,正如[C​​0]所指出的,如果要保持代码格式而不是内联,则需要将James Coyle标签包装在<code>标签中。


0
投票
<pre>
© www.soinside.com 2019 - 2024. All rights reserved.