skip to Main Content

I have the following code:

<!DOCTYPE html>
<html>
  <head>
  <style>
code {
  display: inline-block;
  padding: 0;
  color: red;
}
p > code:only-child {
  display: block;
  white-space: pre;
  padding: 20px;
  line-height: 125%;
  background: #eee;
  border: 1px solid #ccc;
  margin: 1em 0;
}

  </style>
  </head>
  <body>
<p>Assuming you have the IP <code>1.1.1.1</code>:</p>

<p><code>
echo "hello world";
echo "another command here";
echo "you are done";
</code></p>
</body></html>

But it’s causing the page to look like this:

enter image description here

The problem is that the p > code:only-child is also selecting the <code>1.1.1.1</code>. What is the CSS rule to select a <code> element if and only if it is an only child element and it does not have any non-space character sibling?


Note: I am not able to edit HTML because it’s been created by another software I don’t have access too. I am also not allowed to use JavaScript. I only have authority to add my own CSS code.

I have about 1000 other HTML documents like this where there is a <p>some text<code>/etc/path-to-conf</code>some text</p> and others that are <p>text<code>...</code>text<code>...</code>...</p> and others that are <p><code>...</code></p>. I don’t want to manually go through each html document one at a time to write a custom css selector. Only when <code> element is only child element without non-space character siblings should appear as a block level element. All other <code> elements should appear as inline-block.

2

Answers


  1. The provided code is functioning correctly. It selects code in both instances as there are no other elements present aside from the code. If you believe this might pose an issue, consider using:

    <p><span>Assuming you have the IP</span><code>1.1.1.1</code>:</p>
    

    This modification introduces a element alongside within the paragraph for potential adjustments.

    Login or Signup to reply.
  2. Maybe like this:

     p:has(code) code {
            color: red;
        }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    
    <body>
        <code>1.1.1.1</code>
        <p>HELLO <code>1.1.1.1</code>
            <span>ONE <code>two</code></span>
        </p>
        <p>WORLD <code>1.1.1.1</code></p>
        <code>1.1.1.1</code>
    
        <p>1.1.1.1</p>
    </body>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search