What is the best way to align a collection of images in HTML and CSS?

Struggling to center five PNG images on a simple website for a friend. Previously, using display: block; and margin: auto; for one picture worked, as shown below. However, my current code:

.middleContent{
        width: 100%;
        top: 50px;
        position: relative;
    }
    
    h2{
        font-family: helvetica;
        font-size: 15px;
        text-align: center;
        float: left;
        width: 20%;
        position: relative;
        top: 30px;
    }
    
    .middlePhoto1, .middlePhoto2, .middlePhoto3, .middlePhoto4, .middlePhoto5{
        width: 15%;
        padding-right: 2%;
        padding-left: 2%;
    }
<div class="mainContent">
    <img class="topContent" src="img/homepage.jpg"></img>
    <div class="middleContent">
    <img class="middlePhoto1" src="img/icon1.png"></img> 
    <img class="middlePhoto2" src="img/icon2.png"></img>
    <img class="middlePhoto3" src="img/icon3.png"></img>
    <img class="middlePhoto4" src="img/icon4.png"></img>
    <img class="middlePhoto5" src="img/icon5.png"></img>
    </div>
    </div>
    

After making some edits, the images now appear in the center of the screen but not quite centered on the screen. Despite using only 5% padding right and plenty of pixel space to the left, the fifth icon still won't fit. Frustrating, right?!

Answer №1

Consider the following approach:

.middleContent{
    /* Center the content using text align */
    text-align: center;
}

.middleContent1, 
.middleContent2, 
.middleContent3, 
.middleContent4, 
.middleContent5{
    /* Display as inline-block elements */
    display: inline-block;
}

Alternatively, instead of assigning individual classes, utilize CSS selectors for styling:

.middleContent > img {
    /* Display as inline-block elements */
    display: inline-block;
}

The issue lies with the float: left; property. Floats interfere with margin: auto as they are designed to wrap other items around them. Consider removing the float property as it may not be necessary in this context.

Update

If you aim to float two blocks centered next to each other without gaps, you can achieve this using font-size and inline-blocks. Here's a suggestion:

html {
    /* Define a base fontsize for browser resetting (using rem unit) */
    font-size: 16px;
}

.middleContent {
    /* Eliminate gaps between inline-block elements by setting font-size to 0 */
    font-size: 0;
    /* Set a percentage width for scalability */
    width: 50%;
    /* Specify a max-width to limit scaling */
    max-width: 200px;
}
.middleContent * {
    /* Ensure text can be contained within the block */
    /* Define font-size in pixels for older browsers */
    font-size: 16px;
    /* Reset font-size to rem value for modern browsers */
    font-size: 1rem;
}

Answer №2

To enhance the appearance of the image container called middleContent, it is recommended to include the style margin: auto and adjust the width of the images accordingly. It is advisable to stick to modifying styles in the CSS for better organization. By eliminating the width attribute from the images and incorporating a new CSS rule for them, you will have more precise control over their presentation. I have set up a jsFiddle demonstration to illustrate my suggestion. Instead of utilizing multiple classes, you can simply use a CSS selector like .middleContent img.

.middleContent {
    width: 50%;
    margin: auto;
}

.middleContent img {
    width: 20%;
    float: left;
    display: block;
}

Answer №3

If you're looking to center align the content, you can use the following code snippet:

.centerContent1,
.centerContent2,
.centerContent3,
.centerContent4,
.centerContent5 {
  align: center;
}

For a demo, you can check out this fiddle link: http://jsfiddle.net/xyz123/4/

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

Using AngularJS to dynamically bind HTML content based on a variable’s value

I am trying to dynamically display an image of a man or a woman on a scene, depending on the gender of the person logged into my website. The ng-bind-html directive is working fine when I define "imageToLoad" statically. However, it fails when I try to gen ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

Ways to Retrieve the Text From the Selected Index in Datalist Element

I need to extract the inner text of the option tag using pure JavaScript This is the HTML code I am working with: <input list="in" name="i_n" class="form-control" placeholder="Enter Item Name" required> <datalist id="in" onChange="rate(this)"&g ...

positioning the cursor at the end of a content-editable div

When working with a contenteditable div, I encountered several issues specific to FireFox. To address these problems, I found that appending a br tag to the end of the div was necessary. <div id="testDiv" contentEditable="true"> Hey, click the butt ...

Personalized sorting to match the unique rendering of cells in Material UI Data Grid

I have integrated the Material UI V4 Data Grid component into my React Js application. The Data Grid component requires two props: rows (list type) and columns (list type). Below is a sample row item: const rows = [ { id: 1, customerName: " ...

Can HTML code be saved in "context" and then utilized in one of the templates?

I am striving to extract the code of a table from another website using selenium, save it in the context dictionary, and then embed it into one of the templates so that it seamlessly becomes part of the page's HTML structure without displaying the cod ...

Vue calendar - The month display is condensed to only one row

Currently, I am incorporating bootstrap-datetimepicker for Vue (found at https://www.npmjs.com/package/vue-bootstrap-datetimepicker) via CDN. The date display looks good, however there is an issue with the month view size when selecting a month. https://i ...

Ensure that the HTML link is valid and authenticated using SESSIONS

When creating a website, one of the initial tasks I like to tackle is adding links at the bottom of the page for checking valid HTML and CSS: HTML5  •   CSS <div> <a href="http://validator.w3.org/check?uri=referer" ...

Issues with styled-components media queries not functioning as expected

While working on my React project with styled components, I have encountered an issue where media queries are not being applied. Interestingly, the snippet below works perfectly when using regular CSS: import styled from 'styled-components'; exp ...

Tips for keeping two divs aligned horizontally on a webpage

Currently diving into the world of Bootstrap 5, I am facing a challenge with keeping my links and the label "Testing" on the same line. Despite using text-start and text-end classes, they refuse to cooperate. How can I ensure that they both stay aligned ho ...

Display image in PHP as a JPG, not in ASCII format

When trying to display an image after using fopen and fread, I am encountering an issue where the image appears as ASCII code rather than in its proper format. After doing some research, I came across a solution: Fopen function opens JPEG image as text ...

How to change the border color of a Bootstrap card when hovered over

I'm struggling to achieve a border color change effect on hover for Bootstrap cards. <b-card no-body class="my-card border"> <button>Click here</button> <b-collapse> <b-card-body> <b-c ...

Is there a quicker method for iterating through every pixel in a Python image?

Looking to process an image in Python where I need to find the average location of all "acceptable" pixels within a specified boundary. The image is black and white, with acceptable pixels having a value of 255 and unacceptable pixels having a value of z ...

How can we nest a div within the outermost parent element?

Consider a scenario where there are 3 different divs named grandParent, Parent, and Child. Although the parent's tag is placed inside the grandParent, due to the use of position: absolute; property, the parent ends up being displayed outside the grand ...

Can a TypeScript variable in Angular contain a mixture of HTML and plain text?

I have a website where I am displaying content from a Model file. I would like to create a TypeScript variable that contains both a string related to the website's content and a URL enclosed in an HTML tag. When this variable is rendered on the view, ...

There seems to be an error with JVectorMap: the <g> attribute transform is expecting a number but is instead receiving "scale(NaN) translate(N..."

Hey there! I'm currently working on creating a form with a map to select the country of birth using JVectorMap. However, when checking the Google Chrome developer console, I encountered the following error message: jquery-jvectormap-2.0.5.min.js:1 Err ...

What could be the reason behind the appearance of borders in my modal window?

I can't seem to find the source of the 2 silver borders in my modal. I've checked the CSS code, tried using developer tools, and looked through the entire code but still can't figure it out. Here is the JSX code I'm working with: impor ...

Exploring Cypress techniques for testing the HTML5 intrinsic validation popup

Is there a way to detect an HTML5 built-in popup validation error while testing an app with Cypress? It seems that this error does not appear in the DOM, making it challenging to capture using a cy command (I am utilizing testing-library). https://i.sstat ...

How can I eliminate excess cell spacing from a div that has a display of inline table?

This situation is really frustrating. While using Firefox and Opera, I am encountering unnecessary padding between my nested divs, which is not the case with Chrome and Safari. I attempted to use border-collapse:collapse However, it did not work. Do you ...

Looking to switch up the thumbs-up button design?

I am a beginner in using jquery and ajax, and I need some assistance. How can I incorporate this jquery code into my logic: $('.btn-likes').on('click', function() { $(this).toggleClass('liked'); }); Can so ...