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

Stop Internet Explorer from automatically scrolling when it gains focus

Please access this fiddle using internet explorer (11): https://jsfiddle.net/kaljak/yw7Lc1aw/1/ When the page loads, the <p> tag is focused and Internet Explorer slightly scrolls the element so that the table border becomes invisible... document.qu ...

simplest method to brighten the image in this specific instance

I have a simple question. We are looking to enhance some static images by adding a lightening effect with an overlay. For example, when hovering over an image like on this website: (just for the lightening effect). What is the best approach to achieve thi ...

How can I use jQuery to reload the page only at certain intervals?

I'm currently using jQuery to reload a page with the code provided below: <script type="text/javascript"> $(document).ready(function(){ setInterval(function() { window.location.reload(); }, 10000); }) & ...

What is the most effective method for implementing a background repeated image in Foundation 4 framework?

Currently, I am utilizing the foundation4 framework for my website. In order to achieve a repeating tiled background, I have crafted a custom CSS file and included the following code snippet: body { background: url(img/floorboardsbg.jpg) repeat; } Whi ...

Auto-collapse sidebar upon clicking anywhere on the page

I have a dynamic sidebar that appears when the user clicks on a hamburger button. Here is the layout: $('#nav-toggle').click(function() { if($('#nav-toggle').hasClass('active')){ $('.menu').animate({ r ...

How can I populate a <select> tag with options dynamically using C# when the page loads?

I am using jQuery ajax to populate cascaded dropdown elements from a database. The issue I'm facing is that I can't seem to add the default "Select Program" option at the top of my first dropdown dynamically. Even though I tried using the prepend ...

Providing a user with a special discount tailored to their email address?

<script type="text/javascript"> function updatePrice() { var price = document.getElementById("product").value; var size_price = document.getElementById("size").value; var a=parseInt(price);//parsed type price var b=parseInt(size_price);//pa ...

Ways to retrieve base64 encoded information from an image within an HTML document

On my registration form, users have the option to select an avatar from 2 choices: Select a default avatar Upload their own custom avatar This is how I have implemented it in my HTML page. <img id="preview" src="img/default_1.png"> The chosen av ...

Exploring the use of color in text embellishments

Is it possible to change the color of the underline on text when hovering, while keeping it different from the text color? I have successfully achieved this in Firefox using the property "-moz-text-decoration-color". However, this does not work in other m ...

How can I incorporate a custom icon into the <i> tag in HTML like Bootstrap does with its icons?

When working with Bootstrap, you can easily add an icon using the following syntax: <i class="bi bi-arrow-right-square-fill fs-1"></i> One great feature is that you can adjust the size of the icon by simply adding the fs-1 class. If ...

Submitting values using the serialize method and Ajax involves sending placeholders

Looking for a solution: <form class="pure-form pure-form-stacked" method="post" enctype="multipart/form-data"> <input type="text" name="name" class="button-size-1" placeholder="*Name"> <input type="text" name="email" class="but ...

Prevent event bubbling when clicking

I have a code snippet that I'm struggling with. <p>haha</p> <button class="btn btn-light" onclick="nextSibling.classList.toggle('d-none');"> <i class="fa fa-ellipsis-h"></i> </button> <div class= ...

What is the best way to show a loading spinner as my Next image component loads, especially when there is an existing image already being displayed?

I'm trying to incorporate a loading spinner or any other HTML element while an image is being loaded. Currently, I am utilizing the ImageComponent to showcase images in a random movie generator. Although I managed to make the spinner work for the init ...

Prevent any pop-up windows from appearing when a specific link is clicked

On my website, I have implemented popup advertising where ads open when clicked inside the body. However, I am looking to disable popups when a link with the class donot is clicked. Currently, when the donot link is clicked, a popup opens and the link doe ...

clicking on links to different sections of the page does not automatically bring you to the top of

I am working on a design similar to this: http://jsfiddle.net/MTWu5/ The layout consists of a centered page with a sticky header. The header contains menu links that lead to anchors within the page. My issue arises when clicking on these links - I would l ...

The subfolder and HTML page have identical names and are not functioning properly

I recently updated my webpage by removing the .html extensions using htaccess. My website includes a page named "blog.html" and a subfolder called "blog" with additional html pages inside. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ ...

The CSS3 Transform feature kicks in only after the window is resized in Mozilla Firefox

I have created a pure CSS3 parallax webpage by following the method outlined by Keith Clark and using a sample made by Carl Henderson (I can't provide a direct link to his codepen due to my lack of reputation). You can find the code in the main page, ...

What are the best ways to ensure a website is responsive in a vertical

When designing a responsive webpage, I encountered an issue with the body element not properly expanding the content vertically. Despite enlarging the web content horizontally, the body failed to adjust its height accordingly, resulting in unwanted black a ...

Imagine a webpage with a width of 1000 pixels. Can you determine the precise horizontal position (from the left) of the div element with the unique id of "inner_div"?

Hello everyone, I hope you're doing well. I recently took a test and unfortunately got this question wrong. Imagine a web page with a width of 1000px. What is the exact horizontal (from the left) position of the div element with id "inner_div"? < ...

Using the last child as a parent element in Selenium with JavaScript

I am trying to access the input element of the last child in this code snippet. Specifically, I want to retrieve the text Text Reply - Delete. <div class="priority-intent-div"> <div class="row add-priority-intent-div"> ...