Adjust column-count property according to the size of the content (CSS dilemma)

I have a variety of paragraphs on my page, with some being lengthy and others very short. I have applied the common property of column-count: 2 to all paragraphs, but I am facing an issue where I do not want to split a paragraph into two columns if it consists of only two or three lines.

Below is the code snippet:

p {
    column-count: 2;
}
<h2>First paragraph (needs to be two columns)</h2>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<h2>Second one (no need of column)</h2>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the </p>

In my content, the first paragraph is long and should be displayed in two columns. However, the second paragraph is short and should not be split into two columns.

Here is a Demo demonstrating a minimal working code example.

Please note that I am unable to predict in advance which paragraphs will be long or short as they are generated dynamically from the server.

Edit: Since my actual code contains over 100 paragraphs, I am looking for a CSS-only solution to address this issue (if possible).

Answer №1

To conditionally enable or disable CSS based on word count, JavaScript must be used as CSS cannot dynamically adjust based on content length.

While JavaScript can be applied on the client side, the short-paragraph class can also be added server-side.

JavaScript Solution

function letterCount(element) {
    return element.textContent.length;
}

function isShort(element) {
    return letterCount(element) < 200;
}

Array.prototype.slice
    .call(document.getElementsByTagName('p')).forEach(paragraph => {
        if (isShort(paragraph)) {
            paragraph.classList.add('short-paragraph')
        }
    });

CSS Styling

p {
    column-count: 2;
}

p.short-paragraph {
  column-count: 1;
}

Try the live demo.

Performance

Concerns about speed? A benchmark test with 500 paragraphs shows it to be efficient (5ms on an old laptop).

Answer №2

.odd {
  column-count: 1;
}
.even {
  column-count: 2;
}
<h2>First paragraph (requires two columns)</h2>
<p class="even">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<h2>Second one (no need for columns)</h2>
<p class="odd">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the </p>

A simple solution: Define odd and even classes for your paragraphs and then customize their styles as needed. Assign the odd class to any paragraphs that should not be displayed in two columns.

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

Slider Volume with jQuery

Struggling to find a solution for this issue. Seeking some assistance. My goal is to create a basic volume slider. So, the orange section represents my volume slider. This is the jQuery code I am using: var mouseIsDown = false; $("#volSlider").on("mou ...

What is the best way to adjust a horizontal list of inline elements to stack vertically when the div container is resized?

Here is the issue I'm facing (notice how the yellow tiles are overflowing): (view image here) because my reputation points are not enough. The screenshot above illustrates how the small yellow rectangles are extending beyond the boundaries of the gr ...

I seem to be having trouble properly sizing the width of my forms in Mui React

Having trouble with the sizing of my tabs in a project I'm working on. The first tab displays ingredients, while the second tab allows for adding new ingredients with various forms. However, when selecting different forms, the width of the form contai ...

Do you need to align images side by side and have clickable images positioned beneath each one?

After searching high and low, I couldn't find a similar question. My goal is to transform this from a vertical layout to a horizontal one: https://i.stack.imgur.com/4kZNM.png Check out the code snippet below: ghost<br class="newline"> <img ...

Does anyone else have a peculiar problem with css width?

Either I have been designing web pages for an extensive period of time without taking a break or something truly bizarre occurred. <div style="background-color:#0F0; margin:5px; height:5px;"></div> This will generate a lengthy bar with a 5-pi ...

Is it possible to specifically focus on Google Chrome?

Can anyone help me with positioning the update button on www.euroworker.no/order? The button works fine in Firefox and Internet Explorer, but it's not displaying correctly in Chrome or Safari. I've tried targeting Safari and Chrome specifically, ...

Is the use of !important included in Bootstrap 4?

Even though I've positioned the style.css file after Bootstrap, it still isn't working. Upon inspection, I noticed that... https://i.sstatic.net/ay621.png How can I solve this issue? .bg-info{ background-color: #17a2b8 !important; } ...

Concealing Bootstrap 3 elements on a split-screen layout

I encountered a peculiar issue with Bootstrap 3. When I resize my browser width to half the screen, there is a slight 1px threshold where both "hidden-xs" and "hidden-sm" elements become visible simultaneously. Is there a way to fix this so that only one o ...

Ways to apply distinct styles to various ids and common classes

When dealing with multiple IDs such as id1, id2, and id3 that share common classes like .selectize-input and .select-dropdown, it can become cumbersome to set styles individually for each ID. Instead of writing: #id1 .selectize-input, #id2 .selectize-inp ...

Reducing the size of CSS classes and IDs

I am searching for a way to automatically compress classes and ids in an .html file. This specific file is generated through a sequence of gulp commands. I attempted to use the Munch command line application, but it had adverse effects on the file by elimi ...

The EJS is causing a problem with linking the style sheet

Currently, I am in the process of familiarizing myself with ejs, express, and node js. Facing an issue while trying to link my style sheet to my header, below is the code snippet and here is a https://i.stack.imgur.com/0BEIn.png. Utilizing include for bo ...

Incorporate a class into a link within the wp_list_pages function

I've been experimenting with creating a hover effect on list items using the wp_list_pages() function in my Wordpress theme. Despite my efforts, I've hit a roadblock in getting the hover effect to work properly. As a beginner in web development, ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

Title Bar: Excessive gap; inaccurate navigation to nearby link

I've been trying to align a horizontal navigation bar right below a banner and link directly to specific sections on the same page. No matter what I do, I can't seem to remove the white space between the banner image and the navigation bar. It ...

Ways to reset a JQuery/JavaScript filter

I am currently working on a list of div items that are being filtered and sorted using JavaScript. Each item animates as it enters the screen, scaling up to its final size. However, when I apply filters using buttons, items that are already displayed do n ...

Unable to locate any division element by using document.getElementById

I'm encountering an unusual issue in my code. I am attempting to change the background color of certain divs using Javascript, but for some reason, when I use "document.getElementById", it is unable to find the div and returns NULL. Here is the probl ...

What is the best way to highlight titles that are unique but still prominent?

.test{ display:none; } .title:nth-child(odd){ background: #ddd; } <div class='title'>lorem</div> <div class='title'>lorem</div> <div class='title test'>lorem</div> <div class='tit ...

Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when send ...

What are the steps for positioning material-ui icons to the right?

I have a list that is dynamically generated with the following code snippet: <list className = "todos-list"> {allTodos.map((todo, index)=> { return ( ...

The animation-play-state is set to 'running', however, it refuses to start playing

I'm in the process of creating a landing page that includes CSS animations, such as fade-ins. Initially setting animation-play-state: "paused" in the CSS file, I later use jQuery to trigger the animation while scrolling through the page. While this s ...