What is the best way to ensure that text moves to the next line if it exceeds the boundaries of the parent div in either CSS or

I am looking to have the "remaining books count" and "remaining pens count text" automatically move to the next line below the numbers when they exceed two digits, causing an overflow in their parent div.

Here is the code snippet I currently have:

function Text() {
    return (
        <wrapper marginTop={marginTop}>
            <View>
                <span>100</span>
                <span>/100</span>
            </View>
           <Text>
               remaining <br />
               <SubText>books count</SubText>
           </Text>
           <Divider />
           <View> 
               <span>100</span>
               <span>/100</span>
           </View>
           <Text>remaining <br />
               <SubText>pens count</SubText>
           </Text>
       </Wrapper>
  );

  const Wrapper = styled.div<{ marginTop?: number }>`
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-top: ${props => (props.marginTop || 0) + 'px'};
  `;

   const View = styled.div`
       display: flex;
       flex-direction: row;
       align-items: baseline;
       margin-top: 8px;
    `;

     const Text = styled.span`
         margin-left: 8px;
     `;

      const SubText = styled.span`
          white-space: nowrap;
      `;

      const Divider = styled.div`
          height: 37px;
          margin-left: 16px;
          margin-right: 16px;
          border-left: 1px solid grey;
      `;


function Parent() {
    return (
        <Wrapper>
            <LeftWrapper>
                <ContentBox height={30}>
                    <Overview />
                </ContentBox>
                <ContentBox height={70}>
                    <Main /> //this is where the Text component is rendered
                </ContentBox>
            </LeftWrapper>
            <RightWrapper>
                <ContentBox height={100}>
                    //some components rendered                           
                </ContentBox>
            </RightWrapper> 
        </Wrapper>
    );
}

function Main () {
    return (
        <>
            <Text/>
        </>
    )
}

const Wrapper = styled.div`
    display: flex;
    flex-direction: row;
    position: relative;
    justify-content: space-between;
    align-items: center;
    align-self: center;
    align-content: center;
    overflow: hidden;
    width: 1200px;
    height: 500px;
    min-height: 500px;
    max-height: 90vh;
    max-width: 90vw;
    flex: 1;
`;

const LeftWrapper = styled.div`
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 336px;
`;

 const RightWrapper = styled.div`
     display: flex;
     flex-direction: column;
     height: 100%;
     width: 864px;
 `;

  const ContentBox = styled.div<{ height: number }>`
      padding: 12px;
      width: calc(100% - 16px);
      height: calc(${props => props.height}% - 16px);
      margin: ${16 / 2}px;
 `;

If the digit does not exceed 3 and therefore does not overflow within the View of the Text component, then I want the text "remaining books count" and "remaining pens count" to be displayed as shown in the example image.

https://i.sstatic.net/WK2MK.png

However, if the digit is more than 2 resulting in an overflow in the parent div, I would like the text "remaining books count" and "remaining pens count" to automatically move to the next line as demonstrated here.

https://i.sstatic.net/YtwON.png

I am seeking advice on how to achieve this layout adjustment, preferably using CSS. Alternatively, a JavaScript solution would also be acceptable. Can someone assist me with this? Thank you.

EDIT:

The Text component must be reusable. The text "remaining books count" and "remaining pens count" should only span to the next line when used within the Main component and nowhere else...

Answer №1

To achieve the desired layout, consider incorporating flex-wrap: wrap; into your CSS.

<Wrapper marginTop={marginTop}>
 <Section>
   <View>
     <span>100</span>
     <span>/100</span>
   </View>
   <Text>
     remaining <br />
     <SubText>books count</SubText>
   </Text>
 </Section>

 <Divider />

 <Section>
   <View>
     <span>100</span>
     <span>/100</span>
   </View>
   <Text>
     remaining <br />
     <SubText>pens count</SubText>
   </Text>
 </Section>
</Wrapper>;

const Section = styled.div`
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
`;

Answer №2

Here's a solution to your issue: Simply include the wrapper--two-lines class when there are 3 digits.

.wrapper {
  display: flex;
  margin-top: 20px;
}

.wrapper--two-lines {
  flex-wrap: wrap;
}

.wrapper--two-lines .left-wrapper {
  width: 100%;
}
<div class="wrapper">
  <div class="left-wrapper">10/10</div>
  <div class="right-wrapper">remaining books count</div>
 </div>

<div class="wrapper wrapper--two-lines">
  <div class="left-wrapper">100/100</div>
  <div class="right-wrapper">remaining books count</div>
 </div>

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

Unable to perform updates for personalized fonts

I've been trying to incorporate custom fonts into my website, but I seem to be facing difficulties in actually implementing them. Could someone please let me know if I am doing it correctly? .pattern{ background:rgba(0,0,0,.5) url(../images/pattern ...

ToggleButtonGroup in Material UI is a great way to create toggle

I am trying to implement the ToggleButtonGroup feature from Material UI in my React application. I am facing an issue where I am unable to pass values into my state correctly. The code snippet provided below shows that while the Select component works fi ...

Stop the rendering of angular attribute directives within the template

When I add some conditional classes and attribute bindings in the template, Angular retains those attribute directives in the DOM, as seen in the developer tools: <input type="radio" name="gender" ng-model="lsmodal.data.profile.gender" value="male" ng- ...

Use a JavaScript function on identical IDs

Can someone please help me figure out how to hide multiple divs with the same id using JavaScript? I attempted the following: <script> function filterfunc() { if(document.getElementById('filter_deductible').value == 'id_50'){ ...

Exploring the capabilities of the Next.js router and the useRouter

import { routeHandler } from "next/client"; import { useRouteNavigator } from "next/router"; const CustomComponent = () => { const routerFromHook = useRouteNavigator(); } export default CustomComponent; Can you explain the disti ...

Expanding the properties of an object dynamically and 'directly' by utilizing `this` in JavaScript/TypeScript

Is it possible to directly add properties from an object "directly" to this of a class in JavaScript/TypeScript, bypassing the need to loop through the object properties and create them manually? I have attempted something like this but it doesn't se ...

How can I assign a URL when a button is clicked in Next.js?

Can I manipulate queryString values using nextjs and reactjs? I have a filter list on my page that changes the displayed results when clicked. I want to update the URL's queryString values so that if a user navigates away from the page and then retu ...

Developing an interactive website utilizing AngularJS, WCF Service, and SQL Server

Exploring the possibilities of creating a web application, I stumbled upon AngularJS. With plans to incorporate WCF Service and SQL Server into my project, I am intrigued by what these technologies can offer. I want to ensure that AngularJS aligns with my ...

My code seems to be malfunctioning - why can't I keep the aspect ratio?

UPDATE: Can someone please assist me with maintaining the aspect ratio of a drawn image? I am struggling to achieve this and would appreciate any help. I have been attempting to upload an image, draw it using the imageDraw() function, and fit it within a ...

Utilizing Images as Backgrounds in JSP

Looking for assistance with adding a background image in a JSP file without overlapping the navigation bar? Check out my code below: <jsp:include page="index_header.jsp"></jsp:include> <div class="container"> <div style=&ap ...

Implement a callback function in React using hooks after changing the state

Back in the days of React before hooks, setting state and calling a function after it had been set was achieved using the following syntax: this.setState({}, () => {//Callback}) Now, with hooks, what is the equivalent way to achieve this? I attempted ...

What is the process for transforming specific words within a sentence into clickable links?

In my experience with React, I faced the challenge of creating links within a string. After experimenting with various approaches, I finally discovered a solution without having to manipulate the DOM directly. function generateProfile() { const hashtagRe ...

What is the reason behind this useEffect triggering an endless cycle of requests to the '/analysis' API on the server?

This Node.js route is handling the backend processing. app.post('/analysis' , async (req , res) => { const {temp , humidity} = req.body.data.current let predictedCrops:any[] = [] let humidityDifference1 let humidityDifference2 let ...

Steps to enable ng-model input HTML in AngularJS

I am working on an HTML code snippet that includes a form input for audio link. However, when I try to enter a URL in the input field and submit the form, I encounter the following errors: <div class="inner-content-linkaudio"> <label for="linka ...

What is the best way to compare an attribute value with a JSON value in JavaScript?

I have a JSON string that looks like this: { "DocID": "NA2", "DocType": "Phase1.1 - Visa Documents (This section is applicable for HK work location only)", "DocSubType": "New Application", "DocName": "Passport / Travel Document (Soft copy only) ...

What is the best way to customize the appearance of the Material-UI Menu Popover using JSS?

Check out my Code Sandbox for the code snippet: https://codesandbox.io/s/0qv1jwlmlv The purpose of this code is quite simple: class SimpleMenu extends React.Component { state = { anchorEl: null }; handleClick = event => { this.setState( ...

Is there a way to retrieve the row and parent width from a Bootstrap and Aurelia application?

Is there a way to determine the exact width of a bootstrap grid row or grid container in pixels using Aurelia? I attempted to find this information on the bootstrap website, but I am still unsure as there are multiple width dimensions such as col-xs, colm ...

Upon page refresh, products are automatically added to the cart

While developing a shopping cart code, I encountered an issue where refreshing the page automatically added a product to my cart without any action from me. For instance, my website displays three products: Apple, Banana, Orange. When I click on Apple, it ...

Tips for creating a responsive tab indicator in Material UI?

I successfully integrated react router with material-ui and the routing system is working as expected. Clicking on a tab routes you to the corresponding component. However, I am facing an issue where the blue underline indicator that typically accompanies ...

Navigating through the drupal module directory using JavaScript

Is there a way to retrieve the module path in Drupal 7 from which a .js file was loaded? Although JS is primarily a front-end language, is it possible that Drupal includes this information within the Drupal object? Essentially, I am trying to achieve so ...