How to decide the layout according to the number of flex children?

Is it possible to adjust layouts in css/html based on the number of child elements?

Below is an example layout for reference.

I have tried using nth-child, but I might not be implementing it correctly...

https://codepen.io/brycesnyder/pen/EvBzWq

My goal is to make all elements occupy 50% width and stack if there are multiple ones.

/* three items */
li:first-child:nth-last-child(3):not(:first-child),
li:first-child:nth-last-child(3) ~ li {
    background: green;
}

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

UPDATE: While it can be done with standard elements like this https://codepen.io/brycesnyder/pen/GvbbyY, I am looking to achieve the same result with just a UL > LI structure

Answer №1

Instead of determining the layout based on the number of children, you can achieve the desired look by adjusting the flex direction to column, setting the width to 50%, and ensuring the first element has a flex property of 0 0 100%. Additionally, you'll need to handle the special case of a list with only one child by setting its width to 100%.

The necessary CSS code will be:

ul {
    padding:10px 1px;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    height: 200px;
    list-style-type: none;
}

li {
    outline:1px solid gray;
    text-align:center;
    width: 50%;
    margin: 0;
    padding: 0;
    flex: 1 1 auto;
}

li:first-child {
    height: 100%;
    flex: 0 0 100%;
}

/* Handle one item case */
li:first-child:nth-last-child(1) {
    width: 100%;
}

Here is a Codepen link where you can see the implementation:

https://codepen.io/kball/pen/yomyyg

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

Tips for implementing vertical scrolling in a Windows 8 app when in snapped view

Currently, I am developing a Windows 8 application using Html, CSS, and JavaScript. Upon entering snapped view, certain screens are unable to display the entire content, leading me to seek a solution for vertical scrolling. Is there a way to address this ...

Fixed position of the rotated button placed at a 90-degree angle on the right side of the screen

Recently, I had a project where I had to include a div that was rotated 90 degrees and fixed to the right side of the screen. The challenge was making sure that as you scrolled down, the button moved along with the screen while maintaining responsiveness. ...

Conceal Choices During Search using jQuery Select2

I'm having trouble figuring out how to make the Select2 plugin work for my specific color selection feature. My goal is to allow users to choose 5 colors from a list, including an "Other" option. When the user selects "Other", they should be able to ...

Experience a seamless transition to the next section with just one scroll, allowing for a full

I've been attempting to create a smooth scroll effect to move to the next section using Javascript. However, I'm encountering issues with the window's top distance not being calculated correctly. I'm looking to have the full screen div ...

Grab a parameter from the URL and insert it into an element before smoothly scrolling down to that

On a button, I have a URL that looks like this: www.mywebsite.com/infopage?scrollTo=section-header&#tab3 After clicking the button, it takes me to the URL above and opens up the tab labeled tab3, just as expected. However, I would like it to direct m ...

Expanding and filling the parent container both horizontally and vertically with Bootstrap 4 cards arranged in columns

Utilizing Bootstrap 4, I have constructed a row with 3 columns, each set to a size of 4 on medium and larger displays. Although the content within these cards may vary in size, my goal is to ensure that each card maintains an equal length. I have opted ag ...

Getting the full referrer URL can be achieved by using various methods depending

I am currently working with ASP.Net. My goal is to retrieve the complete referrer URL when visitors arrive at my website from: https://www.google.co.il/webhp?sourceid=chrome-instant&rlz=1C1CHEU_iwIL457IL457&ion=1&espv=2&ie=UTF-8#q=%D7%90 ...

Why do I continue to encounter the error message saying 'jQuery is not defined'?

As a newcomer to the world of jQuery and Visual Studio Environment, I embarked on the journey of creating a circular navigation menu bar following the instructions provided in this link. Despite my efforts, I encountered a hurdle in the head section where ...

How can I use flexbox to position this footer at the bottom of its parent container?

I'm not an experienced designer and it's been a while since I last worked with CSS. I'm diving into using flexbox layout for the first time and feeling a bit overwhelmed. Here is the existing HTML structure that I need to work with and cann ...

Randomly assigning a unique color to each div upon loading the page

I would like to create an effect where the background color of an icon changes randomly to match the color of the text. There are four predefined color choices available for this randomization. Here is the current code I am working with: HTML: <div ...

Generate a purposely filled css grid with excessive content

I am attempting to design a horizontal scrolling widget that resembles an image carousel but with text and icons. This widget will contain multiple columns, but only one will be visible at a time while the others will have 'overflow: hidden'. T ...

Chrome has trouble correctly displaying SVG when it is inlined in HTML

I generated an SVG file using etree in Python and now I am facing display issues when embedding it into an HTML document. The pure SVG file displays correctly on its own, but once embedded in the HTML, my browser (Chrome) only shows a text field instead of ...

Pressing the enter key should trigger jQuery to submit the form

Whenever a user submits a comment on my site by pressing enter, it works as intended. However, if the user wants to create a new line without submitting the comment (e.g., by pressing shift+enter), how can this be achieved? This is the current code I have ...

Tips for showing all percentages on a Google PieChart

I'm currently encountering two issues. How can I ensure that the entire legend is visible below the graph? Sometimes, when the legend is too large, three dots are added at the end. Another problem I am facing involves pie charts. Is there a way to d ...

The canvas element automatically removes itself after being resized within an HTML5/JavaScript environment

I created a canvas that is interactive and responsive to screen size. However, I encountered an issue where the canvas clears itself when the browser is resized by just one pixel. Is there a way to prevent this from happening? I have included code in my sc ...

Desktop display issue: Fontawesome icon not appearing

Having trouble getting the fontawesome icon to display properly on my website. It appears in inspect mode, but not on the actual site itself. Any suggestions on how to fix this issue? import React, { Fragment, useState} from "react"; import { Na ...

Tips on incorporating animations into a class design?

I'm trying to figure out how to make an image disappear by adding a class However, when I try this, the element vanishes without any animation I'd like it to fade away slowly instead I've heard there are CSS3 properties that can help achi ...

How can you target a custom tag using a wildcard in CSS?

Within my Angular application, I have various component pages such as <app-page-home>, <app-page-login>, <app-page-documentation>, etc. that are displayed when needed in the <router-outlet>. I am facing a challenge where I want to ...

CSS nth-child doesn't target specific element

It appears that the css nth-child selector did not hit its mark. Any ideas on why? Check out the jsFiddle source Here is the HTML structure: <a href="#">red</a> <br /> <a href="#">none</a> <br /> <a href="#">gra ...

Wordpress Website Lagging in Loading Speed

After migrating my Wordpress site from my computer to a Bluehost shared server, I noticed a significant decrease in loading speed. The home page now takes 107 seconds to load, while it ran smoothly on my local machine. Upon running a GTMetrix site analyzer ...