Ensuring the Line Breaks in CSS and JavaScript to Easily Modify the Style

Is there a way to determine when a line will break so I can apply different styles?

The design team needs 3 buttons in a grid (3 columns) with specific sizes. They want buttons with content that breaks onto the next line to have a border-radius of 13px, while buttons whose content fits on one line should have a border-radius of 30px.

A solution with its own problem: My initial approach was to change the class based on the number of characters, but it's not entirely accurate, as shown in the images below.

(18 characters) should have a border-radius of 13px because it breaks onto the next line

(19 characters) should have a border-radius of 30px since it does not break onto the next line

Question: Is there another method to achieve this?

Thank you

Answer №2

To determine the border-radius of a div, consider the height of the div. If the height is greater than 42px (enough for text to be displayed in more than one line), set the border-radius to 20px; otherwise, set it to 13px.

//jquery solution 
$(".div").each(function() {
  if ($(this).outerHeight() > 42) {
    $(this).css("border-radius", "20px");
  } else {
    $(this).css("border-radius", "13px");
  }
});

//pure javascript solution
Array.from(document.querySelectorAll(".div")).forEach((element, index) => {
  if (element.offsetHeight > 42) {
    element.style.borderRadius = "20px";
  } else {
    element.style.borderRadius = "13px";
  }
});

//choose either one
.div {
  border: 1px solid #000;
  display: inline-block;
  padding: 8px;
  font-size: 16px;
  max-height: 42px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div">
  Lorem Ipsun dolor
</div>

<div class="div">
  Lorem <br/> Ipsum dolor
</div>

The height of the div depends on your font properties such as font-size, line-height, font-family, and padding.

Answer №3

Here's a suggestion for you:

Consider setting a fixed width for the text container and calculate how many characters can fit within that width based on the desired line break measurement (e.g. 20px/.5rem/ETC). If the number of characters exceeds the calculated limit, use JavaScript or CSS to force a line break and adjust the border radius accordingly.

While there may be alternative solutions available, this approach could potentially work with some additional tweaks and adjustments.

Answer №4

If you want to check for line breaks in button text using RegEx, you can do so by checking the number of line breaks and applying styles based on the result.

    <script type="text/javascript">
     jQuery(document).ready(function() {
     var btnValue = document.getElementById('btn').innerText;
     var lineCount = (btnValue.match(/\n/g)||[]).length;
     if(lineCount > 0)
     {
        // Apply Styles Here
     }
    
    });
    </script>

    <body style="height:94%;" > ;
        <button id="btn">Lorem ipsum,
        <br>vero accusantium,
        <br>modi repellendus?
        <br>Enim nisi iusto.</button>
    </body>

Answer №5

Appreciation for the assistance provided. The insights shared here helped me broaden my perspective and successfully tackle this issue.

This is how I resolved it: Since I am utilizing react, I implemented a useEffect to add an additional property to my array:

useEffect(() => {
  const heights = itemRefs.current.map((itemRef) => itemRef.offsetHeight);
  setListOfHeights(heights);
  console.log(heights);
}, []);

useEffect(() => {
 if (listOfHeights) {
  let shallowCopy = [...ingredients];
  shallowCopy = shallowCopy.map((item, index) => {
    return {
      ...item,
      height: listOfHeights[index]
    };
  });
  setListOfIngredients(shallowCopy);
 }
}, [listOfHeights]);

I then incorporated a reference and a height condition within my loop:

  <div className="ingredientsWrapper">
    {listOfIngredients.map((item, index) => (
      <div
      key={`item_${index}`}
        ref={(el) => (itemRefs.current[index] = el)}
        className={`ingredient ${item.height > 36 ? 'bigger' : ''}`}
        onClick={() => handleClick(index)}
      >
        {item.label}
      </div>
    ))}
  </div>

Where 36 corresponds to my minimum height (indicating no line breaks)

View my solution in CodeSandbox

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

Updating the Scale of the Cursor Circle on my Portfolio Site

I attempted to find tutorials on creating a unique circle cursor that can hide the regular mouse cursor as well. After implementing it with a difference blend mode, I encountered an issue where I wanted the scale to change when hovering over a link. The ...

Understanding the React Login Flow with Google and Facebook Integration

I'm currently working on incorporating Google and Facebook login features into my React application. As of now, I have added two buttons (one for Google and the other for Facebook) along with their respective code snippets: <GoogleLogin classN ...

Display the JSON data by pressing Enter key instead of clicking on the submit button

I am facing an issue with my MVC view where clicking the submit button posts data using Ajax to the Controller. The controller returns a JSON result containing messages which are then displayed on the View. The problem arises when I press Enter after seein ...

Is there a way to display JSON data in a dropdown list using a Functional component?

export default function FirstStep() { const [ageGroup, setAgeGroup] = useState(''); function getAgeGroup(){ axios.get(`http://localhost:1190/v1/ageGroup`) .then(res => { console.log(res); }) } <Form.Label cla ...

NPM - Include in package.json without installation

Can a command be executed to validate that the package is a legitimate npm package, include it as a dependency in package.json, but refrain from actually installing it? This question arises from the need to utilize a specific package globally and incorpor ...

Compiling Nextjs with Tailwind typically takes anywhere from 8 to 16 seconds

My first time using tailwind has resulted in slow compilation times when used with nextjs in development mode. The slowdown can be confirmed by simply removing the following code: @tailwind base; @tailwind components; @tailwind utilities; This significan ...

Connect with Friends - Using Express, MongoDB, and EJS for a Seamless Friend Connection

I have been working on creating a social network that allows users to send and interact with friend requests. Currently, I have completed the registration, log-in, and "search for other users" functions. Once I find and select another user, I am able to d ...

Triggering an action with a click event on a

[Issue encountered when using const history] I am facing difficulties in utilizing the history hook, despite diligently following the steps outlined on the internet. Any assistance would be greatly appreciated. import React, { Component } from 'react ...

How can the dot badge in Material-UI be enlarged?

I'm in need of a badge component that serves as an indicator without displaying any values. I opted for the dot variant, but it's too small for my liking. I tried modifying it with CSS, but it doesn't seem to be working as expected. Any sugg ...

Twice the fetch is triggered

I've implemented a simple JavaScript function that handles fetching a URL and updating the HTML page upon receiving a response. Here's an example of how it works: function postToDatabase(self) { // other code here async function postData() ...

In Vue.js, when attempting to arrange an array of objects in descending order based on a specific key (such as "name"), the intention is to prioritize data containing uppercase letters to be displayed

I am struggling to organize an array of objects based on a specific key (name). My goal is to have the data with uppercase letters appear first, but for some reason, it's displaying the lowercase data first. I've been using the lodash method "ord ...

Headers are being removed by Express or React

I currently have a basic setup using React and Express. I am in the process of adding headers to a response, but some are not appearing in the React app. On the Express side... app.post('/api/createpdf', (req, res) => { console.l ...

Is feature recognition possible in a jQuery plugin?

Can I integrate a tool similar to Modernizr into my plugin? I want to be able to test for specific CSS3 properties without starting from scratch. ...

What is the reason for the error that is being caused by using arrow functions in my code

I'm currently working on a React application, but I keep running into errors that are causing issues. Here is the code snippet in question: import React from 'react'; import { Link } from 'react-router-dom'; const LINKS = [ { to ...

"Double the fun with fullcalendar.io - where every event is doubled

I am currently using a combination of rails and react.js for my latest project. Let's say I create event A, but then have a change of heart and decide to cancel it via a bootstrap modal. Afterward, I start another event B and proceed to confirm it, ho ...

Is there a way to dynamically display an icon based on its snake_case name in a React material-ui environment?

Typically, I utilize material-ui icons by directly importing them as per the material-ui guidelines. However, in this case, I have a text tag that represents the icon name (e.g. calendar_view_day) and I need to dynamically retrieve and display an icon com ...

How can you verify the presence of an object containing specific data within an array using JavaScript?

Currently, I am working with the Vue programming language and have some demo code to showcase: <template> <button @click="checkInList">Check</button> </template> <script> import { ref } from "@vue/reactivity& ...

Setting up the initial state of a component by retrieving the state value from another component

I am exploring the realm of reactnative/js and diving into the world of asynchronous mechanisms. Despite reading numerous examples, I am still struggling to grasp the concepts clearly. Hence, I have some questions that I hope you can help me with. My curr ...

Tips for modifying the background color of an individual page in Ionic 3 and above

https://i.stack.imgur.com/t2mDw.pngI am just starting with Ionic and I'm attempting to modify the CSS of a single page by changing the background color to something different, like green, for example. I know that I can make global changes, but in this ...

Select items from object based on a specified array of IDs

I am facing a challenge with my list of objects that each have an array associated with them. For instance, take a look at this example: "-KpvPH2_SDssxZ573OvM" : { "date" : "2017-07-25T20:21:13.572Z", "description" : "Test", "id" : [ { ...