Place centered items within a flexbox that uses space-between alignment

When designing a navigation section, I am looking to achieve space-between justification. However, for smaller screens where the navigation items may need to wrap onto multiple rows, I want the items to center themselves instead of aligning to the left when they are alone on a row.

nav {
  display: flex;
  width: 100%;
  flex-flow: row wrap;
  justify-content: space-between;
}
<nav>
  <div class='item'>
    Item 1 will be on its own row on smaller screens but won't be centered.
  </div>
  <div class='item'>
    Item 2 will have a similar layout as item 1.
  </div>
</nav>

Check out the Codepen demo: https://codepen.io/anon/pen/MmdOMP?editors=1100#0

Answer №1

There are a couple of approaches that may work:

  1. Utilize CSS media queries; or
  2. Implement a JS solution, detailed below:

If an item is wrapped and takes up 100% width, you can monitor the window resizing event to determine if the item's width matches that of its parent element. If so, add a specific class at that moment and remove it when the condition is no longer met:

function justifyCenter() {
    var navWidth = $("nav").width();
    var itemWidth = $(".item:first-child").width();

    if (navWidth === itemWidth ) {
        $("nav").addClass('justify-center');
    } else {
        $("nav").removeClass('justify-center');
    }
}

Check out the Codepen demo for a live example: https://codepen.io/anon/pen/WzgpLw

Answer №2

After reading LGSon's comment, it becomes clear that the OP may be looking for a way to adjust dynamic text within a container, regardless of flexbox settings or screen size.

One solution could involve utilizing JavaScript to detect line breaks and then perform an action, such as centering the text. An example library that may assist with this is available at: https://github.com/xdamman/js-line-wrap-detector

Alternatively, consider using JavaScript to automatically resize text to fit the designated container. Although this approach may not be suitable for all scenarios, tools like can be helpful in some cases.

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

How to target a class with a specific number in CSS selectors

My mobile hybrid application is built with Sencha Touch 2 and requires some customization based on the iOS version it's running on. In my Sass stylesheet, I originally had the following selector: .x-ios-7 { /* add iOS7 customizations here */ } How ...

What is the best way to divide the height of one div evenly among three other divs?

I have three child divs inside a parent div and I'm looking to distribute the height of the parent div evenly among the three children. Here is the HTML code: <div class="frameright"> <div class="divright"> <t ...

I have just started a new project in Vue and noticed that the app div has some extra margin around it. Can anyone

In my fresh Vue project, I have the following code: App.vue: <template> <div id="app"> <p>hello</p> </div> </template> <script> export default { name: 'App', components: { } ...

A newline within the source code that does not display as a space when rendered

Written in Chinese, I have a lengthy paragraph that lacks spaces as the language's punctuation automatically creates spacing. The issue arises when inputting this paragraph into VSCode - there's no seamless way to incorporate line breaks in the s ...

Increase the size of a button using CSS styling

Looking for guidance on extending the length of a button in HTML code? Take a look at this snippet: <span class="xp-b-submit xp-b-submit-btn xp-b-right"> <a href="#" class="xp-t-bold" id="PostSubmitLink">Post Search</a> </span> ...

Easy Steps to Align a Rotated Table Header

I am looking to rotate the header table using CSS while keeping all text together. Here is my CSS code: th.rotate { height: 100px; white-space: nowrap; } th.rotate>div { transform: rotate(-90deg); } Here is how I have applied this CSS: ...

Incorporating CSS animations into Vue.js while an API call is being made

When a specific icon is clicked, an API call is triggered: <i class="fas fa-sync" @click.prevent="updateCart(item.id, item.amount)"></i> I am looking to add an animation to rotate the icon until the API call is complete or ...

A rightward sliding submenu that appears upon clicking a button

I have a vision of creating an admin control panel for my website, featuring a set of buttons. I envision that when one of the buttons is clicked, the corresponding sub-menu will appear alongside it. For instance, if "My Account" is selected, its sub-menu ...

"Enhabling tablesorter pagination to ensure that buttons always stay in sync with

I am experiencing an issue with the pagination buttons staying at the bottom of my page, even when there are only 2 entries left on the last page. Check out my table here: Is there a way to make the pagination buttons dynamically move to the top based on ...

iOS users are experiencing issues with mobile responsiveness

I've encountered a strange issue with the mobile responsive design of a website. The website in question is While everything displays correctly on desktop using dev tools > responsive, and on any Android device, the problem arises when viewing it o ...

Styling the elements that are next to each other using CSS

Hey there, what if I have HTML elements structured like this: <div> <div>Name</div> <div><input type="text" class="check"> <div>Age</div> <div><input type="number" class="check"></div> ...

Displaying all items in the flexbox in a single row by decreasing the width of each individual box

After some tweaking, I now have a lineup of boxes styled like this: Check out the code in action on Codepen. Unfortunately, StackOverflow doesn't display it accurately. This is the CSS I implemented: @font-face { font-family: "Heebo-Light"; src: ...

The arrow icon that I included in my bootstrap project seems to have disappeared from my view

While trying to enhance my footer, I attempted to include an arrow-up-circle icon. However, after adding the code, the icon doesn't appear. Here is the html snippet I used: <html> <head> <link href="https://cd ...

The overflow-x property causes the left side of the component to be cut off when scrolling

When the screen width is insufficient to display a component properly, I need it to be horizontally scrollable. However, when scrolling to the left after making it scrollable due to a smaller screen size, the left side of the component gets cut off and can ...

Conceal the scroll bar within a div set to 100% viewport

Having some difficulty with a scrollbar on my new portfolio. The layout consists of two columns, with content on the left. I need the ability to scroll without displaying the scrollbar. I attempted the code below but it did not work. Could the issue be rel ...

Display the item with jQuery once the CSS generated by jQuery has finished loading

Is it possible to delay the visibility of an object until my script finishes loading? I tried using ajaxcomplete() and ajaxSuccess() without success. Check out the code snippet below for an example. There's an image with the id: imagefocus. Whenever ...

Using CSS to align and place elements

Currently facing a challenge with my HTML/CSS code regarding the horizontal centering of two divs (A, B) within one absolutely positioned div (C) that contains background images. Key aspects to consider: The bottom edge of the larger div (A) should alig ...

Using the viewport meta tag in HTML and CSS within Laravel's Blade template while also

Greetings everyone! I have a question regarding Blade Laravel: Can we add a condition to the meta name="viewport" content="width=device-width, initial-scale=0.4"? I want the scale to start at 0.4 for smartphones and at 0.6 for tablets. ...

Having issues with the CSS dropdown menu not activating when hovering

I am facing an issue with a simple menu that includes a dropdown feature upon hovering. The code works perfectly fine in Fiddle, however, it fails to work when running the entire page locally on IE. Can someone please assist me? (here's my code at fi ...

Ways to eliminate hover effect in CSS

I have a text that is currently displayed as a hyperlink, and some CSS code is causing it to underline and become bold when hovered over. I want to remove the hyperlink, but still keep this style by default without needing to hover over the text. Here is m ...