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

What's the best way to align divs vertically in a compact layout?

Update The reason I require this specific behavior is to ensure that all my content remains in chronological order, both on the web page and in the HTML structure. This way, even if the layout collapses into a single column on smaller screens, the content ...

Reposition picture "overlays" additional HTML components

I am struggling with rotating an image by clicking on a button as the image overlaps the buttons. Can anyone provide guidance on how to achieve this without overlapping? For reference, here is my code and an example: here (http://jsfiddle.net/jj03b17n/5/) ...

Move the scroll bar outside of the div and set it to automatically overflow

My issue involves a small div with the CSS property overflow:auto;. However, when the scroll bar appears, it covers up a significant portion of the div. One possible solution is to use overflow:scroll;, but this can result in an unsightly faded scroll bar ...

Retrieve the text content of the paragraph element when its parent is clicked. The paragraph element belongs to a group that contains many

In a function I'm working on, I need to retrieve the specific text within a p element when its parent (.photoBackground) is clicked. The purpose of this operation is to grab the caption for a gallery, where there are multiple p elements with the same ...

sliderLighter: keep the slider moving smoothly at a constant speed

I am currently utilizing lightSlider and I want to create a continuous sliding effect with consistent speed. I do not want any stops or pauses between the images, just a smooth and constant movement. Is it possible to achieve this using lightSlider? Or per ...

Simulating a mobile device screen size using an embedded iframe

Imagine this scenario: What if instead of adjusting the browser window size to showcase a responsive web design, we could load the site into an IFRAME with the dimensions of a mobile screen. Could this concept actually work? Picture having an IFRAME like ...

A step-by-step guide on changing an image

Is it possible to change an image when the user clicks on a link to expand its content? <ul class="accor"> <li> Item 1 <img src="../plus.png"> <p> Lorem ipsum dolor sit amet</p> </li> </ul> $(' ...

Unable to replicate the functionality of the tab key using jQuery for the enter key

How can I focus on the first input ('Qtd on the table') after pressing enter on the 'Buscar' input? I've tried various solutions like $(this).nextAll('input').first().focus(); $(this).next('input:text').focus ...

When attempting to click on my subtopics using jQuery, they do not appear as expected

$(document).ready(function () { $("#subTopics").hide(); $("#mainTopics").click(function () { $("#subTopics").show("slow"); }); }); body { margin: 0; } li, a{ text-decoration: none; list-style-type: none; text-d ...

What could be causing my Bootstrap (3) grid to not display responsively?

It seems like there may be a simple oversight in my code, as I'm unable to make my Bootstrap grid responsive. I have successfully passed item data through Node and am able to display a grid of item thumbnails with captions in rows of 4. However, when ...

Issue with displaying HTML escaped characters such as "&#39" results in showing a pound sign instead of a single quote

Whenever I store data in my Java code, I employ HtmlUtils.htmlEscape to ensure that HTML characters are escaped. However, when retrieving the data and trying to display it in an HTML format (using AngularJS 1.6), the escaped characters (&rsquo;, &am ...

What is the process for converting HTML assets into a SCORM package?

**css styles fonts images media menu1_images menu2_images menu3_images menu4_images** index.html index_custom.js index_actions.js menu1.html menu1_custom.js menu1_actions.js menu2.html menu2_custom.js menu2_actions.js menu3.html menu3_custom.js menu3_actio ...

What causes pagination to be displayed outside of the main section in Firefox when using swiper?

When using swiper, why does pagination display outside of the main section in Firefox when inserting slides with different content lengths? This issue seems to only occur in Firefox and not in other browsers like Chrome. I have noticed that using two boots ...

"Embed a div element over a full-screen iframe or image

Is it possible to create a div within a fullscreen iframe without using JavaScript? I want to achieve a similar layout to the Netflix player, with static buttons and functions in PHP. The div should have a cut background positioned on top of the iframe. ...

Issue with checkboxes preventing submission of form

Currently working on a website project for a company that requires certain steps to be completed for deliveries. Unfortunately, I am facing issues with the submit button, and I apologize as I am still new to this. The code I have pasted is divided into tw ...

Challenges with Knockout.js Virtual Elements in Different Environments

I am facing a peculiar issue where a virtual knockout template fails to bind correctly when accessed remotely, yet functions perfectly when viewed locally. You can find the problematic page here: Here is the template I am using: <ul> <!-- k ...

How can I use the store command to retrieve the href value of a link using a css selector in Selenium?

Is there a way to store a URL from a link using CSS instead of xpath? store //tr[td[contains(.,'6 Day')]][1]/td[8]/a@href my_var open $my_var If so, how can I achieve this goal with css? I managed to use the following locator: store css= ...

State in Angular stubbornly refuses to switch despite condition changes

Here is the Typescript code, followed by the HTML: public verifySelection() { let choice = false; if (typeof this.formUser.permissionsTemplateID === undefined) { choice = true; } return choice; } <div class="form-group" ...

Shopping cart feature in PHP - Ajax response only functioning once

I'm in the process of developing a shopping cart. I start by adding products to the cart, then use Ajax to dynamically update the quantity when it changes. Everything works smoothly after the first change, but subsequent quantity updates do not refres ...

How can you hide specific elements in HTML/CSS based on window size without relying on media queries?

How can I create an HTML/CSS toolbar where specific elements disappear completely when the browser size is decreased, similar to how the favorites bar functions in most browsers? The toolbar should be able to display a varying number of items. In this cas ...