CSS selector for the only child element without any other adjacent sibling elements that are non-space characters

Here is a snippet of my 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>

However, this is causing an issue with how the page displays:

https://i.stack.imgur.com/LtM6O.png

The problem arises from the p > code:only-child selector also affecting the <code>1.1.1.1</code>. What CSS rule can I use to target a <code> element only if it's the sole child and has no non-space character siblings?


Just to note: I am unable to modify the HTML directly as it was generated by inaccessible software. Additionally, JavaScript is off-limits for me. I am only permitted to add my own CSS rules.

I have numerous HTML documents like this one. Some contain segments like

<p>some text<code>/etc/path-to-conf</code>some text</p>
, others have
<p>text<code>...</code>text<code>...</code>...</p>
, and some simply consist of
<p><code>...</code></p>
. I wish to automate the process so that any <code> element which stands alone without non-space character siblings appears as a block level element, while all other instances appear as inline-block elements.

Answer №1

Perhaps it could be done like so:

 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>

Answer №2

The code provided is in working order. It successfully selects the necessary elements as there are no other extraneous elements to consider. If you think this setup could cause a problem, you may want to try the following alternative approach:

<p><strong>Assuming you have the IP address:</strong> <code>192.168.1.1</code></p>

This adjustment adds a strong element within the paragraph alongside the code for potential modifications.

Answer №3

As of now, CSS does not offer a way to target an element that is without any sibling elements such as text nodes.

However, if you have the ability to include a <script> tag similar to how the <style> tag is included, achieving this using JavaScript becomes feasible.

If including scripts is not an option, then altering the HTML generation may be necessary.

<!DOCTYPE html>
<html>

<head>
  <style>
    code {
      display: inline-block;
      padding: 0;
      color: red;
      font-family: ui-monospace,"Cascadia Mono","Segoe UI Mono","Liberation Mono",Menlo,Monaco,Consolas,monospace;
    }
    
    .code-block {
      display: block;
      white-space: pre;
      padding: 20px;
      line-height: 1.25;
      background: #eee;
      border: 1px solid #ccc;
      margin: 1em 0;
    }
  </style>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      [...document.querySelectorAll('p > code')].filter(code => 
        code.parentElement.childNodes.length === 1
      ).forEach(code => code.classList.add('code-block'));
    })
  </script>
</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>

Answer №4

It's unlikely that you'll achieve exactly what is needed using CSS alone, but you can come close (like placing the IP address on the same line as the text and changing its color to black) by targeting the ::first-line of the code element.

Here's an example that demonstrates this:

https://i.stack.imgur.com/2Q7lG.png

<!DOCTYPE html>
<html>

<head>
  <style>
    code {
      display: inline-block;
      padding: 0;
      color: red;
    }
    
    p>code:only-child {
      white-space: pre;
      padding: 20px;
      line-height: 125%;
      background: #eee;
      border: 1px solid #ccc;
      margin: 1em 0;
    }
    
    p>code:only-child::first-line {
      color: black;
    }
  </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>

Please note that the demonstration works in this scenario because there is a blank line within the actual code block, which prevents the first echo line from being selected.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem aligning ul within div element

I'm having trouble aligning my ul element in the center of a div. I tried using the margin: 0 auto method, but it's not working as expected. I've always wondered if setting the width of the ul within a div is necessary for using margin: 0 au ...

problem with the height of the side navigation bar

Currently, I am in the process of creating a back-end system that includes a side navigation bar positioned on the left-hand side. To accomplish this, I have opted to utilize the Bulma CSS framework and integrate it with Laravel. Although I have implemen ...

What is the best way to create a button that can cycle through various divs?

Suppose I want to create a scroll button that can navigate through multiple div elements. Here is an example code snippet: <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> <div ...

What is the best way to create a single HTML file that can showcase several different pages?

I am just starting out in web design, and I am currently working on a hobby project which is an e-commerce site. My issue is that I don't want to manually link every single product page. This would result in a large number of HTML files. Instead, I w ...

Issue with host-context scss rules not appearing in final production version

I am facing an issue in my Angular project where the scss rules that define how components should look when within the context of another component are not being applied when I build for production and put it live. Here is an example: :host-context(my-tabl ...

Transferring the dirty state of the view to the parent form

Within my main form's markup, there is a specific structure that includes a tabset and a selectView method in the controller: <tabset vertical="true" type="pills"> <tab ng-repeat="tab in tabsViews" sele ...

Utilizing absolute positioning with a rotated div element

The situation I am facing involves a parent div and child div. The child div is positioned absolutely with respect to the parent div and has been rotated by an angle of 90 degrees. Due to the fact that the origin is located at the center of the child div ( ...

Is there a potential white-space issue with jQuery CSS in Internet Explorer versions 7 and 8

Recently, we encountered an unusual issue with jQuery and CSS while working on compatibility with IE7 and IE8. Our project involves animations and height measurements, and during the animations, we wanted to prevent text from wrapping. To achieve this, we ...

Combining various types of data into a single dataframe

I have been attempting to extract information from the following website: My ultimate objective is to create a dataframe containing the data from the table, and also add a new column that includes the players' index. For instance, for the top player, ...

Ensure that the text is wrapped properly when implementing innerHTML functionality

Within my Angular 5 application, I am faced with a requirement to display HTML content retrieved from a database. An example of the text stored in the database is: <div><u>Documents and Files</u></div><ul><li>These docu ...

Validation is not being enforced for the input field labeled as 'name' in the form

Can anyone assist me with a form validation issue I'm encountering while working on my project? The validation is functioning correctly for email and institution fields, but it seems to be ignoring the name field. Any suggestions or help would be grea ...

How to position the figcaption within a card?

My card design features a masonry-style layout similar to what you can see here https://codepen.io/daiaiai/pen/VPXGZx I'm trying to add some additional information on top of the images using figcaptions, but my attempts with position:relative haven&a ...

Fixing the Responsive Menu Issues

In order to achieve the desired effect of making the text from menu and logo disappear when minimizing the menu, you can use the following approach: Create a function called `smallNav()` to handle the resizing of the sidebar container: function sm ...

My @media queries are causing me some issues

Struggling with my @media queries. Once I upload my website on github, it fails to scale properly. However, when testing it in Webstorm (JetBrains), everything seems to be working fine. Any assistance would be greatly appreciated! Here is the link to my w ...

Issue with a Jquery toggleClass function not working properly on hover

Hello everyone! I am a newbie in the community and relatively new to the world of web programming. I am encountering an issue that is really frustrating me. I attempted to use this code to add a class when hovering over the ul list element so that I can d ...

Manipulate the default option in a Select field with JavaScript

I'm currently working on a WordPress post editing page and I need to set up a target link: By default, the option is set to "None", but I want to change it to "Custom Link..." with the following details: <select name="imt_team_href" onchange="imt ...

`CSS animation for vanishing line effect`

I want to create an animated logo that gives the illusion of being pulled up by a rope, represented by a vertical black line, from the bottom of the page to the top. As the logo moves upwards, I would like the rope to disappear behind it, but I'm uns ...

Tips for avoiding the display of the overall scrollbar while utilizing grid with an overflow:

In my react-redux application, I am utilizing the material ui Grid component for layout design. The structure of my code is as follows: <div> <Grid container direction="row" spacing={1}> <Grid item xs={3}> ...

Calculate the total width of LI elements and apply it to the parent UL or DIV

Is there a way to calculate the Total LI width and then set the width for the parent div? Here is an example of my code: <ul> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds&l ...

Whenever I insert an http link for FontAwesome, the icons work perfectly fine. However, when I try to host it locally,

After providing the CDN link: <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"> The icons are displaying correctly and everything is working fine. You can view the code on ...