How can I remove leading whitespace in my <pre>/<code> block without removing indentation in my HTML? [duplicate]

落花浮王杯 提交于 2019-12-03 01:48:38

You could try this maybe:

pre, code{
    white-space:normal;
}

Fiddle

Here you go, I decided to come up with something more concrete than changing the way pre or code work. So I made some regex to get the first newline character \n (preceded with possible whitespace - the \s* is used to cleanup extra whitespace at the end of a line of code and before the newline character (which I noticed yours had)) and find the tab or whitespace characters following it [\t\s]* (which means tab character, whitespace character (0 or more) and set that value to a variable. That variable is then used in the regex replace function to find all instances of it and replace it with \n (newline). Since the second line (where pattern gets set) doesn't have the global flag (a g after the regex), it will find the first instance of the \n newline character and set the pattern variable to that value. So in the case of a newline, followed by 2 tab characters, the value of pattern will technically be \n\t\t, which will be replaced where every \n character is found in that pre code element (since it's running through the each function) and replaced with \n

$("pre code").each(function(){
    var html = $(this).html();
    var pattern = html.match(/\s*\n[\t\s]*/);
    $(this).html(html.replace(new RegExp(pattern, "g"),'\n'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
    Here is some code:

    <pre><code>
        Here is some fun code!
        More code
          One tab
            One more tab
            
            Two tabs and an extra newline character precede me
    </code></pre>
</body>

This works, assuming indentation should be based on the first line of code:

//get the code element:
var code= document.querySelector('pre code');

//insert a span in front of the first letter.  (the span will automatically close.)
code.innerHTML= code.textContent.replace(/(\w)/, '<span>$1');       

//get the new span's left offset:
var left= code.querySelector('span').getClientRects()[0].left;      

//move the code to the left, taking into account the body's margin:
code.style.marginLeft= (-left + code.getClientRects()[0].left)+'px';  
code {
  display: block;  //this is necessary for the JavaScript to work properly
}
<body>
    Here is some code:

    <pre><code>
        Here is some fun code!    
          And some more!
            Continuing
          Wrapping up
        Closing code now.
    </code></pre>
</body>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!