Search code examples
htmlcsstext-indent

Why does first line of <pre><code> text display with some indent when formatting is changed with CSS?


I'm trying to change the appearance of code sections on my Joomla 4 website using the Cassiopeia template. A sample HTML source looks like this:

<p>Trying to format a code section below.</p>
<pre><code>This is code line 1, starting at position 1
This is code line 2, starting at position 1 as well
This is code line 3, starting at position 1 as well
</code></pre>
<p>This text follows the code section.</p>

Without adding user CSS, this is displayed as follows:

Screen shot with standard formatting

All lines are left-aligned, as expected.

I'm adding the following CSS to the user.css file:

pre {
    display: block;
    width: auto;
    max-height: 600px;
    overflow: auto;
    background-color: #eee;
    border-radius: 10px;
    border: 1px solid;
    border-color: var(--cassiopeia-color-primary, #111 );
    scrollbar-color: #ccc transparent;
    margin: 20px 40px;
    padding: 30px;
    word-wrap: normal;
}

pre > code {
    font-size: 1.0rem;
    text-indent: 0;
    color: #111;
    white-space: inherit;
    margin: 20px 20px;
}

The CSS (mostly) works as desired, i.e display the code in a bordered box with grey background. However, the first code line is indented by 2 characters. See here:

screen shot with own formatting

I tried to find the cause using Firefox Web Inspecting Tools (shift-crtl-i), but can't seem to find out. What is causing that 2 character indent?


Solution

  • Please update your code a bit, remove margins from styles for the code element and make it a block element:

    pre {
        display: block;
        width: auto;
        max-height: 600px;
        overflow: auto;
        background-color: #eee;
        border-radius: 10px;
        border: 1px solid;
        border-color: var(--cassiopeia-color-primary, #111 );
        scrollbar-color: #ccc transparent;
        margin: 20px 40px;
        padding: 30px;
        word-wrap: normal;
    }
    
    pre > code {
        display: block;
        font-size: 1.0rem;
        text-indent: 0;
        color: #111;
        white-space: inherit;
    }

    The <code> element is inline by default.