Is there a pure CSS way to detect whether the text has wrapped and give it different styles?

Viewed 111

For example, I have a button with a long text on it:

[Please click this button for more information]

Since the text is very long, on some small screens, it would be wrapped.

[Please click this button for more information]

I want to make the text-align as left when it's wrapped and center when it's not.

For instance:

enter image description here

enter image description here

Is there any pure CSS solution for it?

1 Answers

There is no general way to apply different styles to elements at different widths using only CSS. This is a very good thing because it could be very easily broken, as the following example shows (using pseudocode with the form of CSS media queries).

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

CSS

The only way to do it using pure CSS is to find the window width at which the button text is rendered over two lines, and write a media query for that width. For example, if you test your page and find that when it is sized at 500px width or less the button is squished so that the text renders on two lines, you might add the style:

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

Of course, the exact point at which the text is rendered over two lines may differ depending on browser/layout engine.

JavaScript

Using JavaScript you can test the height of each button when the page loads and when the page is resized. If you know the height of the button when it has a single line of text and the button's height is greater than that, then you can apply a different style to those buttons.

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>

Related