Is it possible to use only CSS to determine if text has wrapped and apply different styles to it?

Let's say we have a button with lengthy text:

[Click here to find out more]

Due to its length, the text may be split on smaller screens like this:

[Click here to
find out more]

The goal is to align the text to the left when wrapped and to the center when not. An example is shown below:

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

https://i.stack.imgur.com/91Mmr.png

Is there a CSS-only solution for this issue?

Answer №1

There isn't a one-size-fits-all solution for applying different styles to elements based on their widths using just CSS. This limitation is actually a good thing, as attempting to do so could easily lead to problems, as demonstrated in the following example (using pseudo code resembling CSS media queries).

@element( min-width: 600px ) {
    button {
        width: 500px;
    }
}
@element( max-width: 600px ) {
    button {
        width: 700px;
    }
}

CSS

The only way to achieve this with pure CSS is to identify the window width at which the button text wraps onto two lines and create a media query for that specific width. For instance, if testing reveals that when the page is sized at 500px or narrower, the button's text wraps onto two lines, you might add the following style:

.button {
    text-align: center;
}
@media( max-width: 500px ) {
    .button {
        text-align: left;
    }
}

Naturally, the threshold where text wraps may vary depending on the browser and layout engine being used.

JavaScript

Using JavaScript, it's possible to check the height of each button upon page load and resize. By comparing the height of buttons with single-line text to those exceeding that height, different styles can be applied accordingly.

For example:

function buttonStyles() {
  let buttons = document.querySelectorAll( 'button' )
  for ( let button of buttons ) {
    if ( button.offsetHeight > 40 ) {
      button.classList.add( 'left' )
    } else {
      button.classList.remove( 'left' )
    }
  }
}

window.addEventListener( 'load', buttonStyles )
window.addEventListener( 'resize', buttonStyles )
button {
  width: 300px;
  display: block;
  text-align: center;
  margin: 10px;
  font-size: 15px;
  line-height: 15px;
  padding: 5px;
}
button.left {
  text-align: left;
}
<button>A single line</button>

<button>Two<br>lines</button>

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 could be causing my CSS relative positioning to malfunction?

I am struggling to adjust the positioning of my divs using relative and absolute properties. Any advice on how to resolve this issue would be greatly appreciated. Thank you. Example Code: <div id="game"><img src="gta-game.jpg" height="100" width ...

Support for Arabic in database, PHP, and JavaScript

After inputting an Arabic comment into a textarea on the site, it displays correctly as "عربي" and is successfully sent to the database. However, upon refreshing the page, the text appears garbled: "عربÙ�". I attempted to directly enter s ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

How can I design a versatile button in HTML/CSS3/jQuery/Javascript that utilizes images for borders and corners for maximum scalability?

Is there a way to create a completely scalable button in HTML/CSS3/jQuery+Plugins using images for borders and corners? I have attempted a messy method, but I am confident that there are more effective solutions available. The approach I considered invol ...

Mastering the Art of Defining SVG Gradients in a Page-wide CSS File

On my HTML page, I have implemented a JavaScript code that dynamically generates SVG elements and inserts them into the HTML page. Currently, all the styling attributes such as fill colors are specified in the CSS of the entire webpage. This approach allo ...

When using the navbar in Tailwind CSS, the image is appearing distorted instead of aligning properly with the adjacent

I am trying to add a flag, login button, and sign up button Using class="flex", I placed an image inside it However, when I add the buttons, the image gets distorted. How can I prevent this? Expected Outcome I want to create the flag, login but ...

Ensuring the accuracy of user input

Can someone assist me with comparing two dates in JSP? I need validation that alerts the user when a future date is entered. The start date or end date should not be in the future. The date format is 12-5-2011 10:51:49. Any help would be greatly apprecia ...

JQuery content displaying only on the first instance

<script> $(document).ready(function () { $('nav>li').hide(); $('ul').hide(); $('h2').hide(); $('a.btnDown').click(function () { $('body').css('background&apos ...

Unable to retrieve the value from a textarea when using Shopify Product Options by Bold

I'm currently facing an issue trying to retrieve the value of a textarea using Shopify's Product Options by Bold. The code works fine locally, but when I transfer it over to Shopify, I am unable to get the value. Despite looking at various resour ...

Can you explain the concept of "cascading" within CSS?

Can someone kindly explain the specific definition of "Cascading" in Cascading Style Sheets (CSS)? I have heard conflicting perspectives on this topic, so I am seeking clarification here. Any examples to illustrate would be greatly appreciated. ...

Increasing the upward motion of the matrix raining HTML canvas animation

Recently, I've been experimenting with the Matrix raining canvas animation here and I was intrigued by the idea of making it rain upwards instead of downwards. However, my attempts to achieve this using the rotate() method resulted in skewing and stre ...

Steps to activate highlighting for the initial value in a quarterly datepicker

Concerning the quarterPicker feature in the Bootstrap datePicker (SO: how-to-change-bootstrap-datepicker-month-view-to-display-quarters, jsfiddle: jsFiddle): Is there a way to highlight an initial value upon startup? I have tried setting a value in win ...

using JavaScript to send numerous text box values to various views

I have a dilemma with passing values between two views. In View1, there are text boxes for entering basic information. After the customer enters this data and clicks on 'add more details', I want to transfer these details to the text boxes in Vie ...

Obtain all text within a <div> element by utilizing the agility html package

When attempting to retrieve all <p> tags from within a <div> using the Agility HTML package, I encountered an issue where only the first <p> tag was obtained. <div id='bodayDiv'> <p> hi </p> <p> what is ...

Script for calculating in PHP

I've scoured the internet in search of a sample script that meets my specific needs, but unfortunately, I have come up empty-handed. Essentially, I am looking to retrieve a value from a div and then multiply that number based on user input. For instan ...

Sequentially loading Bootstrap columns as the page loads

Is there a way to load columns one by one with a time gap when the page is loaded? Here's the code snippet that can achieve this: setTimeout(function() { $("#box1").removeClass("noDisplay"); },1000); setTimeout(function() { ...

How to properly format an HTML input box for numeric entry and ensure correct formatting of the minus sign

I need assistance with formatting an HTML text input box to only accept numeric values using JavaScript. Specifically, the input should allow digits, a minus sign, or a dot/comma (which will be converted to a dot). However, I want to prevent multiple conse ...

Vertical centering not functioning as expected due to issues with margin-top and margin-bottom

I'm having trouble centering my red block in the middle of the webpage, with the footer block at the bottom and the white block between them. Oddly enough, margin-top doesn't seem to be working for me, but left and right are functioning fine. Al ...

Revolutionary scroll-based navigation fill transition

I'm attempting to achieve an effect where the fill color of the "insticon" SVG changes from black to white based on the scroll position indicated in the jQuery code. I have made the necessary modifications in the if and else statements, but unlike "he ...

What could be causing disparities in the padding of certain table cells compared to others?

If you're interested, I created a photo gallery over at Take a look around and feel free to download any wallpapers that catch your eye! The issue I'm encountering is with the padding of the columns - specifically, the first and last columns ha ...