The content within an inline-block element exceeds the boundaries of its parent <pre> tag and causes overflow

I'm currently exploring ways to incorporate line numbers into text within a <pre> tag, all while maintaining the ability for the text to wrap. This presents some unique challenges:

  • Adding line numbers in a separate column of a table is not an option, as word wrapping would disrupt their alignment.
  • Line numbers should not be part of the actual text content (they should not be selected or copied along with the text, and wrapped lines should align to the right of the line numbers).

As a solution, I have devised a method involving two <span> elements: one for the line number and another for the text on that line [0]. To prevent the text in the second <span> from wrapping below the first <span>, it is styled as an inline-block:

span {
    display: inline-block;
    white-space: pre-wrap;
}

<pre><span>12345 </span><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
</pre>

However, a setback of this approach is that the second <span> allows the text to wrap beyond the boundaries of the parent <pre>. It appears that the <span> wraps the text based on the width of the <pre>, regardless of its offset due to the first <span>.

Here is a simple example illustrating this issue: http://jsfiddle.net/fgdhyde6/1/

My queries are:

  • What is the reason behind this behavior? This behavior is consistent in both Safari 9.0.1 and Firefox 42.0, indicating it may not be a browser-specific bug.

  • If this behavior is intentional, how can I address it with a more generalized solution (without manually setting the width of the first <span>)?

Update

This issue does not seem to be confined to <pre> tags and specific white-space settings like pre-wrap, as initially presumed. It is also observed with two <span> elements within a <div>: http://jsfiddle.net/fgdhyde6/2/


[0]: Ultimately, the line numbers will be introduced using an appropriate

:before { content: counter(...); }
, preventing them from being included when copying text. Nonetheless, the issue with text overflowing persists regardless of the technique used.

Answer №1

To create line numbers in a code snippet, you can apply padding to the <pre> element and position the line numbers with .line-numbers using absolute positioning.

Here's a tip to simplify the markup: If your code always consists of a line number span followed by a text span, you can target them using pre>span:nth-child(2n-1) instead of the class .line-number:

pre {
  border-style: solid;
  padding-left: 3rem;
  vertical-align: top;
  display: inline-block;
  white-space: pre-wrap;
}
pre>span:nth-child(4n+4) {
  background-color: #e5e5e5; /* this is just so you can see the size of it */
}
.line-number {
  position: absolute;
  left: 1rem;
}
<pre><span class="line-number">12345</span><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
<span class="line-number">12346</span><span>Yr fap deep v pop-up occupy, pug mixtape lo-fi disrupt butcher. Keffiyeh umami yuccie disrupt cold-pressed migas. Fap offal pinterest, +1 retro squid tilde VHS street art thundercats tacos tote bag. </span>
<span class="line-number">12347</span><span>Cray direct trade photo booth, messenger bag taxidermy chillwave retro pitchfork kickstarter. Franzen echo park meggings photo booth cronut, swag cred chicharrones meh neutra dreamcatcher knausgaard church-key.</span>
<span class="line-number">12348</span><span>Gentrify forage chillwave hammock fashion axe bushwick, fap sartorial viral typewriter seitan squid health goth knausgaard selvage. Post-ironic intelligentsia kale chips blog.</span>
<span class="line-number">12348</span><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
</pre>

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

Is there a method to check if my input fields are filled before the bootstrap modal can be triggered in PHP?

Is it possible for the modal button to validate if the textboxes before it are empty? If they are, can we prevent the user from proceeding until they are filled? Check out the code below: <form class="form-horizontal form-signin-signup" action="signup ...

Attempting to align input fields and spans side by side

Is there a way to properly align multiple inputs next to each other with dots in between, resembling an IPv4 address? Currently, the span appears to float in the center. How can this be resolved? It's worth noting that all elements in the image have b ...

Is it possible to resize an image while also adjusting the size of its container using CSS?

I have a block of content with an image sandwiched between paragraphs. <p class="bodytext">aslkjfsdlkfj f ldflskl</p> <p class="image"><img src=1.png/></p> <p class="bodytext">aslkjfsdlkfj f ldfl ...

Unexpected Placement of CSS Grid Items

I am currently facing an issue with aligning items in a nested grid using grid-column/grid-row assignment. After setting the template with grid-template-rows:/grid-template-columns, I expected the $50 and Give Now items to appear on row 3, with one in colu ...

SASS: a common thread connecting multiple applications

The scenario involves a web platform that aggregates various React apps, each with its own .scss files. The goal is to extract the common .scss into a library for convenience. Any suggestions on how best to accomplish this? It's important to note that ...

Converting Umbraco Json to a CSS class named "[]"

I'm currently using Umbraco with the data-type grid layout and I am trying to add custom settings (CSS classes) to each row/cell. The results are somewhat working, but I want to improve it. Here's the user interface: https://i.stack.imgur.com/iY ...

Stylish dots emerging under navigation bar

Okay, so I've run into a simple issue, but I can't seem to figure out the solution. Ever since I wrote this code, I've noticed these small dots appearing below the menu. Take a look at the image for a clearer picture. https://i.sstatic.ne ...

Create a vertical scrollable feature for the <ul> element when it is set to flex, limiting its height within the specified dimensions

In order to enhance user experience, I have implemented a live search bar that is only visible on mobile screens. For the CSS styling: .search-results { z-index: 9999; width: 80vw; position: absolute; top: 80%; left: 10%; } .search-results li ...

Experience a unique double scrolling effect using the react-spring parallax and react-three-fiber Canvas components

My goal is to create a scrolling box with a parallax effect, but I'm facing an issue where it won't bind with the Canvas element, even when both are included under the same div. In the screenshot provided, you can see div1 and div2 each having t ...

Aligning angular bootstrap modal window in the center vertically

Is there a way to vertically center a modal window on the screen, regardless of the size of the content being displayed? I'm currently using an image as a modal window in my page, and while I was able to align it horizontally, I'm struggling to g ...

Validation with Javascript can trigger the display of a hidden element

Hello there, I could really use some assistance with the JavaScript part of this code. I have two JavaScript functions: one for validating if a radio checkbox is selected, and another for revealing the "answer". Currently, an alert pops up if no selections ...

The JavaScript function modifies the value stored in the local storage

I'm in the process of developing a website that requires updating the value of my local storage when certain JavaScript functions are executed. Currently, I have this code snippet: localStorage.setItem('colorvar', '#EBDBC2'); I&ap ...

Using CSS to show only the central portion of an image

How can I display only the center part of an image with dimensions height=300px and width=520px using CSS or jQuery? I tried searching on Google, but didn't find a solution. Is it possible to show only a 200x130 section from the center of an image us ...

Does vuetify offer a card footer or card deck feature in its designs?

I'm trying to achieve a layout similar to this: https://getbootstrap.com/docs/4.0/components/card/#card-groups https://i.sstatic.net/HxKEh.png The goal is to keep the height of the box consistent even when the description varies Here's my code ...

What are the steps to achieve the desired PrimeFaces theme appearance for selectOneMenu?

Need help with a JSF Primefaces project using the omega theme. The selectOneMenu dropdowns are not displaying correctly (missing line). Current look: https://i.stack.imgur.com/vF4ms.png Expected look: https://i.stack.imgur.com/hXsIB.png Any suggestion ...

Trouble with the functionality of the Bootstrap collapse button

I am facing an issue where clicking on the collapse button does not trigger any action. I have tested it on both of my laptops, ruling out any problems with the web browser. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

Reorder the nested list structure

Hello there and thank you for stopping by! I am facing a challenge with a list containing multiple nestings. I am interested in changing the order of these two lists, and I am curious if this is achievable using only CSS. List item 1 List item 2 List ...

The hierarchy of CSS in Vue components

I've developed a customized CSS framework to streamline the design process across all my internal projects. The central file is structured as shown below: @import "~normalize.css/normalize.css"; @import "_variables.scss"; @import "_mixins.scss" ...

Switching the menu based on screen size successfully functions for the div element, however, it does not

Currently, I am working on creating a responsive menu. The structure of my menu is set up as follows: HTML: <ul id="top-menu"> <li class="active"> <a href="#">HOME</a> </li> <li> <a href="#div2">ABOUT</ ...

Issue with border in Bootstrap Grid Navigation Bar

I've experimented with margins, padding, and border options extensively, but I still can't get rid of the white space at the end of my navbar. Can anyone provide a simple solution, please? See the attached image for a clear visual of the issue. T ...