Guide on how to align multiple divs at the center of a container using CSS

Experimenting with centering a divider in the style of Windows metro.

.container {
    height: 300px;
    width: 70%;
    background: #EEE;
    margin: 10px auto;
    position: relative;
}
.block {
    background: green;
    height: 100px;
    width: 100px;
    float: left;
    margin: 10px;
}
<div class="container">
  <div class="block">1. Company Name</div>
  <div class="block">2. Company Name</div>
  <div class="block">3. Company Name</div>
  <div class="block">4. Company Name</div>
  <div class="block">5. Company Name</div>
  <div class="block">6. Company Name</div>
  <div class="block">7. Company Name</div>
  <div class="block">8. Company Name</div>
</div>

The grey box is set to 70% width and centered correctly on the screen. However, when widening the window, the green dividers become misaligned. How can this issue be resolved?

Any suggestions or solutions would be greatly appreciated!

Answer №1

In my previous response, I shared an outdated method to achieve a certain layout (although it still works, there are now better ways to accomplish the same result). To stay current, I am updating my answer with a more modern approach using flexbox.

You can check the browser support for flexbox here; in most cases, it is safe to use.

This updated solution makes use of:

  • display: flex: Setting elements to display as flexbox items
  • justify-content: center: Aligning inner elements centrally along the main axis of the container
  • flex-wrap: wrap: Ensuring that inner elements automatically wrap within the container without breaking out

Note: In HTML & CSS, there are multiple ways to achieve the desired outcome. It's essential to research thoroughly and choose the right method based on your specific requirements.

.container {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    width: 70%;
    background: #eee;
    margin: 10px auto;
    position: relative;
    text-align:center;
}

.block {
    background: green;
    height: 100px;
    width: 100px;
    margin: 10px;
}
<div class="container">
    <div class="block">1. name of the company</div>
    <div class="block">2. name of the company</div>
    <div class="block">3. name of the company</div>
    <div class="block">4. name of the company</div>
    <div class="block">5. name of the company</div>
    <div class="block">6. name of the company</div>
    <div class="block">7. name of the company</div>
    <div class="block">8. name of the company</div>
</div>

Original Answer

The style text-align:center; applied to your container and displaying .blocks as inline-block elements was previously recommended:

.container {
  width: 70%;
  background: #eee;
  margin: 10px auto;
  position: relative;
  text-align:center;
}

.block {
  background: green;
  height: 100px;
  width: 100px;
  display:inline-block;
  margin: 10px;
}
<div class="container">
    <div class="block">1. name of the company</div><!--
 --><div class="block">2. name of the company</div><!--
 --><div class="block">3. name of the company</div><!--
 --><div class="block">4. name of the company</div><!--
 --><div class="block">5. name of the company</div><!--
 --><div class="block">6. name of the company</div><!--
 --><div class="block">7. name of the company</div><!--
 --><div class="block">8. name of the company</div>
</div>

For an updated demonstration, you can view this Fiddle.

Please note that I have removed white-space between the <div>s since they are displayed inline, ensuring proper spacing. This technique is one of several ways to manage space between inline-block elements. You can find more information about this here.

Answer №2

To achieve a different layout for your website, try updating the style of the .block element by replacing float:left; with display:inline-block;. This adjustment will allow you to include text-align:center in the .container.

.container {
  height: 300px;
  width: 70%;
  background: #EEE;
  margin: 10px auto;
  position: relative;
  text-align: center
}

.block {
  background: green;
  height: 100px;
  width: 100px;
  margin: 10px;
  display: inline-block;
}
<div class="container">
  <div class="block">1. name of the company</div>
  <div class="block">2. name of the company</div>
  <div class="block">3. name of the company</div>
  <div class="block">4. name of the company</div>
  <div class="block">5. name of the company</div>
  <div class="block">6. name of the company</div>
  <div class="block">7. name of the company</div>
  <div class="block">8. name of the company</div>
</div>

Answer №3

To ensure compatibility with IE7, you need to update your CSS as follows:

.main { text-align:center; }
.item { display:inline-block; *display:inline; zoom:1; vertical-align:top; }

For aligning the bottom tiles to the left side, a bit of javascript is required. The code below works on all browsers including IE8+ due to backward compatibility with .querySelector(); for simplicity and IE7 support, it's recommended to use jQuery:

if (!window.addEventListener) {
    window.addEventListener = function (type, listener, useCapture) {
        attachEvent('on' + type, function () {
            listener(event);
        });
    };
}
window.addEventListener('load', applyPadding, false);
window.addEventListener('resize', applyPadding, false);

function applyPadding() {
    var mainContainer = document.querySelector('.main');
    var items = document.querySelectorAll('.item');
    var buffer = [],
        maxVal = 0,
        index = 0;
    var topPos = items[0].getBoundingClientRect().top;
    while (items[index] && items[index].getBoundingClientRect().top == topPos) {
        index++;
    }
    var gap = items.length % index ? index - items.length % index : 0; /* calculate number of paddings needed */
    var paddingElements = document.querySelectorAll('.padding');
    if (paddingElements.length < gap) { // add missing paddings
        index = gap - paddingElements.length;
        while (index--) {
            var element = document.createElement('div');
            element.className = 'padding';
            element.style.visibility = 'hidden';
            mainContainer.appendChild(element);
        }
        paddingElements = document.querySelectorAll('.padding');
    }
    for (index = 0; index < paddingElements.length; index++) {
        paddingElements[index].style.display = (index < gap) ? 'inline-block' : 'none';
    }
}

Live demo on jsfiddle

Answer №4

Experience the power of using Flexbox property as a foundation for your layout designs. This enables you to have better control over the positioning and alignment of child elements within the container.

.container {
    width: 70%;
    background: #EEE;
    margin: 10px auto;
    position: relative;
    display:flex;
    flex-wrap:wrap;
    justify-content:center;
}
.block {
    background: green;
    height: 100px;
    width: 100px;
    margin: 10px;
}
<div class="container">
  <div class="block">1. name of the company</div>
  <div class="block">2. name of the company</div>
  <div class="block">3. name of the company</div>
  <div class="block">4. name of the company</div>
  <div class="block">5. name of the company</div>
  <div class="block">6. name of the company</div>
  <div class="block">7. name of the company</div>
  <div class="block">8. name of the company</div>
</div>


Please Note: Before implementing Flexbox in your projects, be sure to validate the browser support and consider adding any necessary vendor prefixes. As of April 2017, most browsers do support this feature.

Answer №5

.container {
  background: lightgrey;
  height: auto;
  width: 70%;

  margin: 10px auto;
  position: relative;
  
  display: flex;
  flex-wrap: wrap;  
  justify-content: space-around;
}
.block {
  background: green;
  height: 100px;
  width: 100px;
  
  margin: 10px;
}
<div class="container">
  <div class="block">1. company name</div>
  <div class="block">2. company name</div>
  <div class="block">3. company name</div>
  <div class="block">4. company name</div>
  <div class="block">5. company name</div>
  <div class="block">6. company name</div>
  <div class="block">7. company name</div>
  <div class="block">8. company name</div>
</div>

Answer №6

<body>

<div class="container">
       <div style="width:78%; margin:0 auto;">
        <div class="block">1. name of the company</div>
        <div class="block">2. name of the company</div>
        <div class="block">3. name of the company</div>
        <div class="block">4. name of the company</div>
        <div class="block">5. name of the company</div>
        <div class="block">6. name of the company</div>
        <div class="block">7. name of the company</div>
        <div class="block">8. name of the company</div>
    </div>
</div>
</body>

Consider utilizing this div "

<div style="width:78%; margin:0 auto;">
" for styling purposes.

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

Achieve centered alignment for a website with floated elements while displaying the complete container background color

I am currently working on a website that consists of the basic elements like Container, Header, Content, and Footer. The container has a background-color that should cover the entire content of the site, including the header, content, and footer. However, ...

The HTML element containing a React variable is failing to render ASCII characters

I am encountering an issue where a custom title, received and set in a JS variable, is displaying the ASCII code instead of the symbol. To illustrate, here is a basic example of the render function: render() { var title = "My Title&#8482;" retur ...

How can you achieve the functionality of jQuery's hide() and show() in JavaScript?

Is there a JavaScript equivalent to my simple hide and show jQuery code? Here is my current code: $(document).ready(function() { $("#myButton").hide(); $("#1").click(function() { $("#myButton").show(); $("#myButton").click(function() { ...

Does using .detach() eliminate any events?

I have a DIV that is filled with various content, and I am using the detach() and after() functions to move it around within the document. Before moving the DIV, I attach click events to the checkboxes inside it using the bind() function. Everything seems ...

If the text is a single line, center it. However, do not center the text if it

Can we center align text horizontally if it occupies a single line, but refrain from center aligning and use white-space: normal when the text spans multiple lines (ideally without the need for JavaScript)? ...

Troubleshooting problems with contenteditable and input in Firefox and Safari on Angular 5

Currently, I am in the process of creating a table with cells that are editable. However, I am facing a challenge in updating the visual and typescript code simultaneously. I have explored various alternatives but unfortunately, none of them seem to work. ...

Exploring the placement and animation of a Flexbox dropdown menu

I'm currently working on designing a header with three main elements: ---------- LOGO ---------- hidden navigation bar ---------- BUTTON ---------- This header layout is supposed to grow into the following structure: ---------- LOGO ------ ...

Challenges arise when working with arrays: Attention required - Offset 0 undefined

I have encountered a challenge with my PHP code. I am attempting to convert an HTML table into an array and then execute a mysqli query, but I am unsure about the process. In my code, I have a variable $aDataTableDetailHTML[][]. The first set of brackets ...

The footer should always be anchored at the bottom of the webpage, maintaining a consistent position regardless of any changes to the browser's

I've successfully implemented a footer with several buttons that remains positioned at the bottom of the page, 60px above the very bottom, regardless of the content or window size. The CSS I'm using is as follows: #container { min-height: 10 ...

Having trouble connecting to the webserver? Make sure the web server is up and running, and that incoming HTTP requests are not being blocked by a firewall

While working on my Visual Studio 2013 Asp.Net web code using the Local IIS Web server Version 7 (Windows 7 x64) and Framework 4.0, I encountered an error message stating: "Unable to start debugging on the web server. Unable to connect to the webserver. V ...

Unveiling the Magic: Transforming Objects into HTML Attributes using AngularJS

I have been working on developing a highly dynamic ng directive that creates tables based on a given data array and configuration object. I am looking for a way to assign attributes dynamically based on an object within the scope. For example, if I have an ...

Is it possible to use multiple stylesheets with PhoneGap?

Currently, I am storing a stylesheet (CSS file) from the web server into device storage using the file system access method provided in the phonegap guide for File. I need to apply this stylesheet to my app from the device storage, and will be updating the ...

Changing a p element to a div and adding a class in Bootstrap 4.5

To maintain consistency, I prefer using <div class='something'>BIO</div> over <p>BIO</p>. In Bootstrap 4.5, is there a similar class that achieves the same result? I'm not very skilled in CSS, so please forgive me i ...

Conceal certain digits of a credit card number in a masked format for security purposes

Is there a reliable method to mask Credit Card numbers in password format within a text field? **** **** **** 1234 If you are aware of a definitive solution, please share it with us. ...

What is the process for setting a linear gradient border color on a table row's border?

Currently, I am attempting to apply a linear gradient border color to the table row. Below are the codes for the table: td:first-child { border-left: 1px solid black; border-bottom-left-radius: 50px; border-top-left-radius: 50px; } td:last-child { bor ...

Is there a way to properly direct to an internal page while utilizing [routerLink] and setting target="_blank" without triggering a full page reload?

I'm attempting to use [routerLink] along with target="_blank" to direct to an internal page without triggering a full app reload. Currently, the page opens in a new tab, but the whole application is refreshed. Here is the HTML: <a [routerLink]=" ...

Encountered a parsing error while attempting to include the navigation bar page

<?php echo <<< END <!DOCTYPE html> <!-- --> <html> <head> <title>Nav</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0 ...

Ways to time animations differently and activate two animations at the same time in every loop

I have 3 hidden text boxes that I want to fade in and slide down simultaneously by 40px when the DOM loads. They should be staggered so that each one triggers after the previous animation finishes. Below is the relevant JavaScript code snippet: jQuery(fu ...

Sending unstyled HTML content using JavaMail

Can anyone offer guidance on sending an email using JavaMail with unformatted HTML tags? Here is the code I am currently using: public void sendMail() throws MessagingException, IllegalStateException, IllegalArgumentException { Properties properties ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...