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

What could be the reason for my Express server returning a 404 error for all files other than index.html?

Currently, I am delving into Node.js with Express in order to set up a small server for educational purposes. Strangely, every request made to files linked within my index.html file, such as the .css, .js, and image files, results in a response code 404. ...

Controlling the window opener; Inserting text into an element in the parent window

A pop-up window allows users to select files, then displays the selected image's URL. However, I need to take additional steps beyond that. I am seeking a method to input the URL into an input element on the parent window. window.opener.document.wri ...

Tips for organizing a grid to achieve the desired layout

Overview I am working on organizing items within the MUI Grid. The grid consists of multiple dynamic rows and columns. Each row has a fixed first column, followed by a variable number of scrollable columns. The scrollable columns should be grouped togethe ...

Only implement the CSS styles if there are multiple elements that have the same class

I have 2 cards with the class card displayed within a card-stack. There can be any number of such cards. <div class="card-stack"> <div class="clear"><button name="clear" value="Clear all" onclick=&qu ...

Creating custom events in a JavaScript constructor function

Just beginning to learn JavaScript. I have a custom function that I want to assign events to in the constructor. var myFunction = function(){ /* some code */ } myFunction.prototype.add=function(){ /* adding item*/ } Now I am looking to add an event to ...

Creating a webpage that dynamically loads both content and video using HTML and Javascript

I designed a loading page for my website, but I could use some assistance. The loading page remains visible until the entire HTML content is loaded and then it fades out. However, I am facing an issue because I have a background video that I want to load ...

What is the best way to display a webpage within an iOS app using PhoneGap?

In my iOS phonegap app, I am looking to have a single view that displays a web page. Can someone guide me on how to load this specific view with a particular URL using JavaScript? Although I primarily develop native iOS applications and do not have expert ...

Configuring Stylelint in a NextJS project using Emotionjs

I recently encountered an issue while trying to integrate Stylelint into a new NextJS Typescript project with EmotionJS. Many rules were not working in my styles files, and the only error I could identify was Unknown word CssSyntaxError. This particular U ...

What method can I use to ensure that the sidebar stays fixed at a particular div as the user continues to scroll down the

Is there a way to automatically fix the sidebar once the user scrolls down and hits the top of the .Section2? Currently, I have to manually enter a threshold number which can be problematic due to varying positions across browsers and systems. Fiddle htt ...

I am looking to utilize the data from a POST request to dynamically update the DOM through a script.js file. How can

After sending a post request, I am looking to update my database and then use an array to dynamically update the HTML content. However, I am struggling with how to pass this data to my script.js file. Here is my progress so far: SERVER let expenseAmo ...

Can you help me make a JavaScript Random Number Generator that utilizes HTML input fields and buttons?

I am currently working on developing a random number generator that takes user input through HTML. The idea is to have the user enter two values and then click "submit" to receive a random number within that range. However, I seem to be stuck at this poin ...

Can you tell if there are any distinctions between the two code snippets?

Initial Code console.log('Begin'); // output 1 await axios({ method: 'post', url: '<HTTP_URL>' data: <SOME_DATA>, }).then ((response) => { // Performing some action... This may take a few seconds. con ...

Examine the syntax of JavaScript

I've been digging into a piece of code written by another person. My focus is on uncovering the JavaScript function that executes when the link below is clicked.... <a href="#subtabs_and_searchbar" id="finish_counting" onclick="$(' ...

Limiting the height of a grid item in MaterialUI to be no taller than another grid item

How can I create a grid with 4 items where the fourth item is taller than the others, determining the overall height of the grid? Is it possible to limit the height of the fourth item (h4) to match the height of the first item (h1) so that h4 = Grid height ...

React - updates to server values do not display in DOM right away

When I work from the client side, I have a modal in my HomeComponent that allows me to select an element. My goal is to then display that selected element within the same HomeComponent (in the productosEnVenta function). The element chosen in the modal is ...

At what point does Math.random() begin to cycle through its values?

After running this simple test in nodejs overnight, I found that Math.random() did not repeat. While I understand that the values will eventually repeat at some point, is there a predictable timeframe for when it's likely to happen? let v = {}; for ( ...

Why does React component still use old state when re-rendering?

I recently encountered an issue with my code. I am using an array of objects in my state, and when I delete an item from the array, the component does not render correctly without the deleted object. Additionally, when I try to open another object (trigger ...

show button after the page has finished loading

I have a button similar to this: <input type="submit" id="product_197_submit_button" class="wpsc_buy_button" name="Buy" value="Add To Cart"> However, I am encountering an issue where if the user clicks the button before all scripts are loaded, an e ...

Why is the Javascript code outputting undefined and NaN during execution?

As a newcomer to the world of javascript, I am venturing into learning its fundamental concepts. In my quest for knowledge, I've dabbled in file reading and came up with a small script which you can find below. // Incorporating the fs (filesystem) mo ...

A dynamic modal window built with ReactJS

I am struggling to understand how to make my app function properly. There is a component called ContactAdd that should render the component ModalWindow when clicked. The ModalWindow component requires a parameter called isOpened={this.state.open}. How c ...