How can we apply Flexbox space-between but exclude single-item rows?

When working with two divs that need to sit at opposite sides of the parent container, using a flexbox with justify-content: space-between is ideal. However, an issue arises when the flex items wrap, causing them to be left-aligned due to only having two total items.

Is there a way to center-align rows with single items?

<div style="display: flex; justify-content: space-between; flex-wrap: wrap">
<div style="background: orange">
<strong>Canvas Prints</strong><br>
<span style="font-size: 14px; color: #ff0000">Create a masterpiece for any wall in your home!</span>
</div>
<div style="background: pink">
<img width="176" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTEAPU9xK-mE81DSwYqh_uMb_EUuqXT1yWzIvs9j7diGY-FHh6X">
</div>
</div>

(You can also check out the fiddle for a better visualization: https://jsfiddle.net/xv6oa418/1/)


Additionally: One suggestion was to add flex: 1 to the first child div, but it's preferred for text in the left div to not wrap unless absolutely necessary (specifically after the second flex item wraps onto the next line). The second div will contain an image, as reflected in the updated fiddle and snippet.

Answer №1

After some experimentation, I was able to solve the issue on my own. By applying flex-grow: 1 to the first/left div and margin: auto to the second/right div, I achieved the desired outcome. This setup allowed the first div to expand and take up all available space, preventing the auto margin of the second div from interfering. As a result, when the content wrapped, the second div was no longer obstructed by the first one, allowing the auto margin to centrally align the second div.

Here is an example:

<div style="display: flex; justify-content: space-between; flex-wrap: wrap">
<div style="background: orange; flex-grow: 1;">
<strong>Canvas Prints</strong><br>
<span style="font-size: 14px; color: #ff0000">Create a masterpiece for any wall in your home!</span>
</div>
<div style="background: pink; margin: auto">
<img width="176" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTEAPU9xK-mE81DSwYqh_uMb_EUuqXT1yWzIvs9j7diGY-FHh6X">
</div>
</div>

(You can also view the code snippet on the fiddle here: https://jsfiddle.net/xv6oa418/2/)

Answer №2

.parent {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}


.text {
  background: orange;
  padding:10px;
  border-radius:10px;

}

.text:only-child {
  background-color: green;
  margin:0 auto;
}
<div class="parent">
  <div class="text">
    <strong>Canvas Prints</strong><br>
    <span >Create a masterpiece for any wall in your home!</span>
  </div>
  <div class="img" >
    <img width="176" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTEAPU9xK-mE81DSwYqh_uMb_EUuqXT1yWzIvs9j7diGY-FHh6X">
  </div>
</div>

You can apply the :only-child selector and set margin:auto to ensure proper alignment of the only child element. Refer to the code snippet above for implementation.

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

Experiencing Difficulty Retaining Checkbox State Using LocalStorage Upon Page Reload

At the moment, I have a script that automatically clicks on a random checkbox whenever the page loads or refreshes. Through localStorage, I can also view the value of the input assigned to the randomly selected checkbox. However, I'm facing an issue ...

Click on the form to initiate when the action is set to "javascript:void(0)"

I am working on an HTML step form that needs to be submitted after passing validation and ensuring all fields are filled. The form currently has an action controller called register.php, but also includes action="javascript:void(0);" in the HTML form. What ...

Convert the regex `[quote="author"]text[/quote]` into a well-formatted div block

I'm attempting to transform [quote="author"]text[/quote] into a properly formatted div block. function bbCode($p_text){ // capturing author $pattern = '/\[quote="(.+)"\]/'; preg_match($pattern, $p_text, $match) ...

No input value provided

I can't figure out what's going wrong. In other js files, this code works fine. Here is my HTML code: <table class='table'> <tr> <th>Event</th><td><input class='for ...

How to eliminate padding between Bootstrap col-xx columns

When using Bootstrap's col-xx classes, the padding can sometimes result in wasted space on smaller screens. To address this, I have decided to remove the padding by nesting col-xx with specific CSS settings like shown below: <style> div[class^= ...

Animate the transformation of a singular property (scale) while neglecting the modification of another (translate)

The issue at hand is the complexity of the transform property, which includes various parts like translate, scale, and more. This is a conceptual query concerning an element, such as .loader, which has transform: translate(10px, 10px) and requires animati ...

I'm looking to generate a semicircle progress bar using jQuery, any suggestions on how

Hi there! I'm looking to create a unique half circle design similar to the one showcased in this fiddle. Additionally, I want the progress bar to be displayed in a vibrant green color. I've recently started learning about Jquery and would apprec ...

Javascript variable unable to retrieve value from textbox

Hey there! I am having some trouble reading a textbox that is populated from the server into a JavaScript variable. When I try to access it, I get a console error saying "can't read from NULL". However, the text box is definitely populated with the st ...

Calculating the computed width based on flex-basis at 0% and the flex-grow factor: what's the deal

Below is an example of HTML with default flex properties being used: <div class="container"> <div class="box"> BOX 1</div> <div class="box"> BOX 2</div> <div class="box box2"> BOX 3 .</div> </div> The ...

A guide on navigating full images using CSS

I am searching for a code that will enable scrolling through entire images on my landing page. It is a bit challenging to explain, but it is similar to the style of scrolling on tesla.com. Each scroll of the mouse wheel moves down one complete image. Can ...

Creating a tooltip that doesn't rely on any child elements

I've been experimenting with creating a tooltip that appears when hovering over an <a> tag and displays a <div> from another location For example: <p> blah blah <a class="tooltiphover">hover me</a> blah blah &l ...

Is there a way to conceal overridden div borders? When two divs are in conflict, eliminate borders only from the overridden region

I am facing an issue with two overlapping div elements. I need to remove the border from the area where they overlap only. Take a look at the code snippet below: <div style="width:100px; height:20px; background-color:#5475b1;border: 2px solid;" ...

issue with manipulating URLs in Express routing

Looking for assistance with Express routing. I want users to only see localhost:3000/page2 when they go to /page2, instead of localhost:3000/page2.html I have three HTML pages - page1.html, page2.html, and page3.html. I've created a server using Expr ...

Position the text of an h1 element next to its corresponding image in HTML5

I'm attempting to create a HEADER element with an H1 tag alongside a logo image. Here is the code snippet: Company name However, the issue is that "Some title" is not displaying correctly as it appears b ...

Maintain the collapsing of links in the navbar with the help of Bootstrap

Currently, I am designing a responsive navigation bar utilizing Bootstrap. The current layout displays as follows: https://i.sstatic.net/KglsX.png in expanded view, and: https://i.sstatic.net/DKvex.png in collapsed view. While the design appears satis ...

Modifying images through resizing and scaling within a flexible web application to accommodate different screen dimensions

With my web application, I have an image that changes in sizes as it calls a different image from the database each time it is viewed. My goal is to make sure this image is displayed responsively on different devices. For smartphones, I want the image to f ...

Convert an R node containing XML nodeset data into either XML or HTML format

Consider a hypothetical node created using xml2::read_html / rvest, for example: require(xml2); require(rvest) doc = read_html('https://www.w3.org/TR/html4/intro/intro.html') e = html_node(doc, '.subtoc') Is there a method to transfor ...

Update the href attribute when a button is clicked

Note: The buttons in the corner will not be submitting the search. The go button would still need to be clicked to submit it. Currently, I am working on a fun project during my free time at work. This project is not meant to be anything serious, but rathe ...

JS not functioning properly in specific pages causing display issues with page height set to 100%

I am facing an unusual issue where certain pages do not stretch to 100% page height in the middle section, causing the left-hand border to be incomplete. For example, on the 'Brentwood' site (please click on the 'Login' link in the top ...

Preserving the scroll position of "md-content" when navigating between various views using "ngView"

While using angularJs and implementing ngView, it's known that scroll position is maintained when navigating back and forth between different views. However, I've incorporated angular material directives like md-toolbar and md-content in my views ...