Is there a way to enable browsers to support line-breaks between inline elements without any spaces separating them?

In the case where I have a container with display: block and I need to dynamically populate it with elements styled as display: inline, such as <span> tags. Each of these elements should act as a "word", so when they reach the right edge of the parent element, they should wrap by inserting a line break before overflowing.

While this can be achieved manually in HTML by adding spaces after each element, doing this programmatically can become messy as it involves manipulating the text content of the parent rather than just working with nodes (considering that nodes may need to be inserted or removed programmatically in any order).

I'm hoping there might be a CSS property for the parent element that specifies to treat the end of any child element as whitespace for better element flow. Any clean solution is welcomed.

View some examples of the desired behavior here (screenshot). The code snippet includes two div tags. The first one demonstrates the desired behavior using whitespaces between spans in the HTML, while the second does not achieve the desired effect due to the lack of whitespaces resulting in no line breaks between spans.

div { width: 200px; background-color: pink; margin-bottom: 10px; }
span { width: 80px; background-color: cyan; }
<div>
<span>text</span>
<span>text</span>
<span>text</span>
<span>text</span>
<span>text</span>
<span>text</span>
</div>

<div><span>text</span><span>text</span><span>text</span><span>text</span><span>text</span><span>text</span></div>

Answer №1

To achieve the desired layout without needing to add spaces between span tags, you can set the parent container's display property to flex and the flex-wrap property to wrap. This will cause the child elements to automatically move to the next line when they reach the edge of the container.

Another option is to use inline-block instead of inline for the elements. This will treat the element as inline while still respecting the specified width and height.

div { 
    width: 300px; 
    background-color: pink; 
    display: flex; 
    flex-wrap: wrap; 
}

span { 
    width: 80px; 
    background-color: cyan; 
    display:inline-block
}
<div>
<span>text</span>
<span>text</span>
<span>text</span>
<span>text</span>
<span>text</span>
<span>text</span>
</div>

<div><span>text</span><span>text</span><span>text</span><span>text</span><span>text</span><span>text</span></div>

This setup allows for programmatically inserting and removing span elements while ensuring they continue to wrap to the next line correctly.

Answer №2

Consider these 2 suggestions for your situation:

  1. You can use css with flex properties and add padding to the <span> elements
  2. If you only require a single space, just include a space before/after your <span> elements

// Another Example
for (let i = 0; i < 8; i++) {
  const item = document.querySelector('.box-2');
  item.innerHTML = item.innerHTML + " <span>text</span>"
}
/* One more Example */
.box-1 {
  display: flex;
  flex-flow: row wrap;
}

.box-1 span {
  padding-right: 4px;
}

.container {
  width: 200px;
  border: 1px solid red;
  margin-bottom: 10px;
}
<!-- Yet another Example -->
<div class="container box-1"><span>text</span><span>text</span><span>text</span><span>text</span><span>text</span><span>text</span><span>text</span><span>text</span></div>

<!-- Final Example -->
<div class="container box-2"></div>

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

WordPress API Encounters a 400 Error with OAuth

While experimenting with the WordPress Rest API, I decided to download a plugin called WP OAuth Server by Justin Greer and managed to set up my own OAuth connection. However, I encountered an issue where I received Error 400 indicating that The grant type ...

Navigate to an external webpage upon clicking using VUE.JS

<h3 :class="{'active': game.Desktop}" @click="game.gameAchievements = false, game.gameCreation = false, enJin.audioController.play('take')" @mouseenter="enJin.audioController.play('cardHo ...

Sending an Array from Javascript to Node.js

First off, I want to express my gratitude for attempting to assist me. I am inquiring about how to pass an Array from JavaScript to a Node.js backend for parsing. Below is the Array in question: var Coordinates = [ {lat: 37.772, lng: -122.214}, ...

Is there a way to rotate a div to exact coordinates?

I am working with two (or perhaps three) coordinates. These coordinates represent the upper left and upper right corners of a shape. My goal is to create a div element where the top-left corner corresponds to the left coordinate, and the top-right corner ...

Resolving Problems with setInterval in jQuery Ajax Calls on Chrome

Seeking assistance in returning the value of a specific URL periodically using jQuery and setInterval. Below is my current code snippet: $("form").submit(function() { setInterval(function(){ $('#upload_progress').load(&ap ...

Tips for making jQuery DataTables switch between multiple DOM tables?

I am working on a project where I need to display different jQuery Datatables based on the selected option in a <select> element. The data for each Datatable is stored in hidden DOM <table> elements: <!-- Make sure jquery.dataTables.css and ...

What is the best way to extract text content from Resx files for utilization in JavaScript code?

Our team is currently working on developing extensive ASP.NET applications for use within company intranets in various languages and cultures. We make use of Globalization techniques with RESX files, utilizing GetResourceText on the server side to retrieve ...

Using Vue.js to share events and data across various components

I am currently working on an application that features a Google map with a places autocomplete controller, similar to the example provided by Google at this link. Whenever an address is searched or selected, or when the map bounds are changed, I trigger a ...

Hunt down the key within the specified array of objects and then proceed to update the value

Exploring the implementation of multiple sorting functionality; the array that holds the field name and sorting order needs to be toggled. Example Click Sort By Name: [{"sortKey":"name","sortValue":"desc"}] Click Sort By Age: [{"sortKey":"name","sortV ...

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...

I want to retrieve a complete HTML page using an AJAX request

I am trying to retrieve the content of a specific page, but encountering issues when using this function: function getResult() { var url="http://service.semanticproxy.com/processurl/ftfu27m3k66dvc3r43bzfneh/html/http://www.smallbiztechnology.c ...

Can someone guide me on how to locate and access the port number?

In my Reactjs project root directory, I've created a .env file. This is what's inside my .env file: PORT = 30001 ... In my App.tsx file, I'm trying to access the port like this: const PORT_NUMBER = process.env.PORT; When I run yarn start ...

MongoDB table collections (table names in other databases)

After setting up my express server to connect to mongodb, I encountered an issue despite everything working fine initially. I created a collection in my mongodb called projects (plural form). In my project.model.js file, I defined the model as follows: c ...

Error: Unable to access the 'receiver_id' property because it is undefined

This function is designed to notify the user when they receive a request in my messaging app for educational purposes. However, I am encountering an issue with the firebase console showing the error: firebase functions. TypeError: Cannot read property &ap ...

Receive live notifications using the Cramp framework in Ruby and Server-Sent Events in HTML5

I have created a demo application to receive real-time updates from the server using Cramp(Ruby) and SSE(HTML5). Encountering the following errors while trying to access the HTML file at http://localhost/sse_time.html: Errors: Chrome: Uncaught Error: S ...

Once map layers have been loaded initially, they will not render again

I'm currently incorporating Mapbox GL into my Vue project using VueMapbox (0.4.1). <template> <MglMap :accessToken="accessToken" :mapStyle.sync="mapStyle" :repaint="true" @load="onMapLoaded ...

Is there a method to incorporate the ".then callback" into useEffect?

Is there a way to utilize the ".then callback" to log the word "frog"? I am interested in viewing my token within the async-storage. Once I have obtained my token, I need to append it to the header of a fetch call. Does anyone know how to accomplish this? ...

Is there a way to ensure that the height of my images matches exactly with its width?

Is there a way to ensure that the height of my images always matches their width? I need the height of the images to dynamically adjust and match the width, even when the window is resized. For example, if the image width is 500px, the height should also ...

Encountering a proxy-related error in an Ionic App triggers a 500 error response

I have a device that is embedded and I am attempting to establish a connection with it through my app using http. In order to achieve this, I am utilizing Ionic Proxy. Within my project file, I have the following configuration: { "name": "MyApp", "ap ...

Exploring the option of eliminating the email field from the PHP redirect function and transforming it into a pop-up notification

I am currently utilizing the following code to send an email notification to my address whenever a new user signs up: <?php $errors = ''; $myemail = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0ded1ddd ...