Struggling to make images wrap properly using flexbox

I've been struggling to get these images to wrap properly within my container. They keep overflowing beyond the designated width and I'm not sure if it's because I have paragraphs placed under each image. Any ideas on how to make 3 images appear in a row at the top, followed by 2 more right below with their titles centered beneath them?

Here's the CSS code snippet I've been using:

.block2 {
  background-color: black;
  width: 100%;
}

.pics {
  display: flex;
}

.pics img {
  height: 200px;
  width: 300px;
  margin: 20px;
  flex-shrink: 0;
  justify-content: center;
  flex-wrap: wrap;
}

.pics p {
  flex-wrap: wrap;
}

And here is an example of the HTML structure:

<div class="block2">
  <div class="text2">
    <h2>Tea of the Month</h2>
    <h1>What's Steeping at The Tea Cozy?</h1>
  </div>

  <div class="pics">
    <img src="images/img-berryblitz.jpg" alt="berryblitz">
    <p>Fall Berry Blitz Tea</p>
    <img src="images/img-spiced-rum.jpg" alt="spicedrum">
    <p>Spiced Rum Tea</p>
    <img src="images/img-donut.jpg" alt="donut">
    <p>Seasonal Donuts</p>
    <img src="images/img-myrtle-ave.jpg" alt="myrtle">
    <p>Myrtle Ave Tea</p>
    <img src="images/img-bedford-bizarre.jpg" alt="bedford">
    <p>Bedford Bizarre Tea</p>
  </div>
</div>

Answer №1

Flexibility is at the core of flex design - with a flex container housing all its flex items.

https://i.stack.imgur.com/DI7AI.png

https://i.stack.imgur.com/0GOgX.png

Typically, a flex container aims to squeeze all items into one line, which may be causing your content to appear cramped. The img and p elements are directly under the flex container, leading to this layout issue.

If you wish to transition to a second line display, consider adding flex-wrap: wrap; to the CSS of your flex container (.pics). While this will allow elements to wrap, it might not fully address your requirements.

To group an img and a p together within the flex container, consider enclosing them in a div:

<div class="pics">
  <div class="pic">
    <img src="images/img-berryblitz.jpg" alt="berryblitz">
    <p>Fall Berry Blitz Tea</p>
  </div>
   ...
<div>

This way, the paragraph and image will remain paired. Customize styles such as centering by targeting each item individually within .pic.

For more insights on flexbox, refer to this comprehensive guide. This should set you on the right path, although there are numerous ways to leverage flex's capabilities!

Answer №2

To achieve the layout of three items in the first row and two items in the row below, follow these steps:

  • When using flexbox, ensure you have a wrapper for both the image and description (you can use figure to wrap them),

  • Apply flex-wrap: wrap to the flex container rather than the flex item,

  • Use flex-basis or width (such as flex-basis: 33.33%) on the wrapping flexbox to display 3 items per row

Check out the demo below with explanatory comments:

.block2 {
  background-color: black;
  width: 100%;
}

.pics {
  display: flex;
  flex-wrap: wrap; /* wrapping flexbox */
}

.pics figure {
  margin: 0; /* reset default margin of figure */
  margin: 10px; /* space between flex items */
  flex-basis: calc(33.33% - 20px); /* 3 items in a row - adjust for the 10px margin on each side */
}

.pics img {
  display: block;
  height: 100px; /* height of each row */
  width: 100%;
  object-fit: cover; /* fit as cover maintaining aspect ratio */
}

figcaption {
  color: #fff;
}
<div class="block2">
  <div class="text2">
    <h2>Tea of the Month</h2>
    <h1>What's Steeping at The Tea Cozy?</h1>
  </div>
  <div class="pics">
    <figure>
      <img src="https://placekitten.com/200/300">
      <figcaption>
        Fall Berry Blitz Tea
      </figcaption>
    </figure>
    <figure>
      <img src="https://placekitten.com/200/300">
      <figcaption>
        Spiced Rum Tea
      </figcaption>
    </figure>
    <figure>
      <img src="https://placekitten.com/200/300">
      <figcaption>
        Seasonal Donuts
      </figcaption>
    </figure>
    <figure>
      <img src="https://placekitten.com/200/300">
      <figcaption>
        Myrtle Ave Tea
      </figcaption>
    </figure>
    <figure>
      <img src="https://placekitten.com/200/300">
      <figcaption>
        Bedford Bizarre Tea
      </figcaption>
    </figure>
  </div>
</div>


If you want to arrange n items in a row using flexboxes, check out the following resources for more insights:

  • 5 items per row, auto-resize items in flexbox
  • How to start a new line with a particular item with Flexbox?

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

Creating a "briefing" iframe at the top of a webpage

I'm looking for a way to allow users to embed my iframe at a specific size, like 100x100, and then have it resize dynamically to fit the page size when they click on it. I want this functionality to work regardless of how the HTML embedding the iframe ...

The AudioContext feature is functioning properly on Google Chrome but experiencing issues on Safari

In Safari, I understand that audio context needs to be created after user interaction. Despite this knowledge, the code below still didn't produce the desired result. HTML <button onclick="play">Play</button> Javascript functio ...

PHP Script unable to locate results

For some reason, the script I have written is not functioning properly. Upon reviewing the code from walmart.com, I verified that name="query" is accurate. However, I am uncertain about the contents within <script></script> <html> < ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

Integrate Arduino's capabilities with Johnny-Five within an HTML JavaScript document

As a beginner in the world of JavaScript, I set out to embark on a project involving turning on a connected LED on an Arduino board by simply pressing a button on an HTML page. After doing some research, I came across a JavaScript library called "johnny- ...

Navigating Up a Directory with JQuery

Is there a way to navigate up one directory level in my jQuery code? The code below is referencing a folder named "uploads" on the C drive, but I can't find any mention of "uploads" in my HTML. How does it know to look there? And how can I go back to ...

The width of the child box does not properly receive the 100% application

Artistic Inspiration I have created a unique and elegant card layout design. * { box-sizing: border-box; } .card { display: flex; width: 600px; height: 400px; } .card > .img-window { width: 100%; background-image: url('https://s3- ...

When you click, a new webpage opens within my website, similar to the feature on Facebook

When using Facebook on mobile, clicking on a link to a person's website opens the website in front of the Facebook page. However, when users press the X in the top left corner, it deletes the webpage but keeps Facebook open. On my desktop computer, I ...

Generating HTML tables with charts using FireFox

I am encountering an issue: My table contains charts and tables that are displayed correctly in browsers. However, when I attempt to print it (as a PDF) in Mozilla Firefox, the third speedometer gets cut off, showing only 2.5 speedometers. Using the "s ...

Click on the logo to return to the home page

Logo Link Causing Menu Alignment Issue After setting the logo as a link, the menu unexpectedly shifts to the right. Upon inspecting the menu element, it appears that there is an additional hidden menu link on the left side leading to index.html. Can anyon ...

Capture all parameters in the URL, regardless of their names

Hello, I am currently utilizing the s:url tag to create a URL in my JSP file for pagination purposes. The issue I am facing is that when clicking on the previous link, it generates a URL in the address bar like someAction?previuos=prev. Similarly, when cli ...

transfer chosen data from a text box to a dropdown menu

Looking for: I am in need of a feature where users can input a movie title in a textbox and upon clicking the "move to selectedlist" button, the entered movie title should be added to a dropdown list that displays all the movies selected by the user. Addit ...

A method for calculating the product of two selected numbers and then adding them together

I am currently working on a form that includes two select options; one for logo design and another for letterhead design. Users should be able to choose the quantity of each design, or both if they wish. For example, a user could select 2 logo designs and ...

Utilizing Backward and Forward Navigation with AJAX, JavaScript, and Window.History

TARGET Implement Ajax for fetching pages Utilize JavaScript to update the window URL Leverage Window History to preserve Ajax page for seamless forward-backward navigation without reloading the page Modify the Navigation bar's attributes (such as co ...

Leverage the retrieved JSON data from the database within an HTML template using the Play

Currently, I am facing a challenge with implementing a login feature in my project. I am struggling to figure out how to showcase the JSON string that is returned on the webpage. Below is a snippet of my code: Security.java: public Person webLogin(Perso ...

Personalized form outlines

I'm designing a Valentine's Day theme for my website and I was wondering if it's possible to create custom form borders, like a heart shape, without having to hard-code everything. I could always insert an image where needed, but that seems ...

Tips for adjusting column sizes in react-mui's DataGrid based on screen size

I would like the title column to occupy 3/4 of the full row width and the amount column to take up 1/4 of the full row width on all screens sizes (md, sx...). Here is the updated code snippet: import React from 'react' const MyComponent = () =&g ...

How can I duplicate or extract all the formatting applied to a specific text selection in Ckeditor?

I am currently utilizing CKEditor version 3.6 within my Asp.net MVC 3 Application. One of my tasks involves creating a Paint format option similar to Google Docs. I am looking to integrate this feature into CKEditor. Is there a way in CKEditor to transfe ...

Trouble Aligning Bootstrap Dropdown Menu Link with Other Navbar Links

Issue with dropdown links not aligning properly in the Bootstrap navbar. The positioning seems off and can be seen in the screenshot provided where the blue outline represents the ".dropdown" https://i.stack.imgur.com/QmG7v.png Facing a similar problem a ...

Unable to convert cursor to jpg format

I am facing an issue where I have a jpg file stored in the same folder as my styles.css, and I want to change the cursor on a webpage to this particular jpg file. Despite my efforts, it seems like the cursor is not changing as expected. Currently, I am us ...