9

I've noticed that any modification of the <code>'s style with respect to its width doesn't have any effect. It's seems to always be set to "auto".

I'm just trying to have some code written inside a <code> tag (this tag is mandatory due to some known iBooks bugs) that has 100% width. One workaround is to put the <code> inside a <div> which has a 100% background style. This works OK but I'll have to deal with a couple of hundred <code> tags... This is the reason I would prefer just to be able to modify the <code>'s width.

Any thoughts? Thanks.

Chris
  • 27,210
  • 6
  • 71
  • 92
Yeseanul
  • 2,787
  • 4
  • 21
  • 25
  • 1
    http://www.w3.org/TR/html401/struct/text.html#h-9.2.1 Notice, CODE is considered and "inline" element, which width/height does not affect as it's width is determined by the content. Per Rob W below, you have to convert it to render as a block, which inline-block can work. – jmbertucci Mar 12 '12 at 16:09

3 Answers3

13

<code> elements are inline elements. Setting a height or width on these do not have any effect on their size.

Use display:inline-block::

code {
    display: inline-block; 
    width: 100px; /* Whatever. The <code>'s width will change */
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
5

Add a display: block or inline-block as per your requirement to the code element. Rest should work as planned

See an example

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Starx
  • 77,474
  • 47
  • 185
  • 261
  • This method does not allow other content at the same line: http://jsfiddle.net/YnQ5m/1/ – Rob W Mar 12 '12 at 16:10
  • @RobW, Generally when you displaying codes, its not necessary to show them in a straight line. That's hardly the case for me. – Starx Mar 12 '12 at 16:13
  • The question, and your answer is full of `` examples. Markdown turns backticks into `` environments. – Rob W Mar 12 '12 at 16:16
  • @RobW, That is not the point. And either way, I have also written in my answer to include `inline-block` to but `as per the requirement` – Starx Mar 12 '12 at 16:20
  • 1
    If the intent is to make the element 100% wide, as the question suggests, then `display: block` is preferable: better browser support (and more logical—if it’s 100% wide, it isn’t really inline). – Jukka K. Korpela Mar 12 '12 at 17:29
2

I think great way to solve this problem is by using CSS Layout - Overflow Here i have used Tailwind CSS. you can use raw CSS to do this task.

     <pre className="overflow-auto bg-gray-900 text-white p-5">
        <code className="text-base font-light ">{yourCode}</code>
      </pre>
CsAlkemy
  • 152
  • 1
  • 6