Home > Enterprise >  How to make code element not go outside pre tag when screen is small?
How to make code element not go outside pre tag when screen is small?

Time:11-28

I have this code:

<pre><code>
<!-- some code -->
</code></pre>

and I'm center it with flexbox. But when the screen is small the code tag go outside the pre-tag. Here is my code:

pre {
    width: 100%;
    border: 1px solid black;
    display: flex;
    justify-content: center;
    min-width: 100%;
    box-sizing: border-box;
}
code {
    display: inline-block;
}

https://codepen.io/jcubic/pen/zYEOovQ

How can I make the pre tag, to always be the same as code, not 100% max? I've tried to use float: left on the flexbox element but I think that float is ignored when using flexbox.

This is probably a common problem, but I was not able to find the question on SO.

CodePudding user response:

Add white-space: break-spaces; to your <code> rules:

pre {
  border: 1px solid black;
  float: left;
  justify-content: center;
  box-sizing: border-box;
}

code {
  display: inline-block;
  white-space: break-spaces;
}
<pre><code>
&lt;!DOCTYPE html&gt;
&lt;html lang="pl-PL"&gt;
     &lt;head&gt;
         &lt;meta charset="utf-8"&gt;
         &lt;meta name="description" content=""&gt;
         &lt;meta name="keywords" content=""&gt;
         &lt;title&gt;Tytuł strony&lt;/title&gt;
         &lt;link rel="stylesheet" href="style.css"&gt;
     &lt;/head&gt;
     &lt;body&gt;
         &lt;p&gt;To jest paragraf&lt;/p&gt;
     &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

To shrink the <pre> to match the code width, remove the width and min-width settings.

CodePudding user response:

You can work with css overflow:auto.

div.scrolli {  
  overflow: auto;
  white-space: nowrap;
  border: 1px solid black;
}
<div class="scrolli">
    <pre>
       <code>
&lt;!DOCTYPE html&gt;&lt;html lang="pl-PL"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="description" content=""&gt; &lt;meta name="keywords" content=""&gt; &lt;title&gt;Tytuł strony&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;To jest paragraf&lt;/p&gt; &lt;/body&gt;&lt;/html&gt;       
        </code>        
    </pre>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related