Populate a div with divs using automatic margins (CSS)

I know this question has probably been asked before, but I've searched high and low and can't seem to find an answer. It seems like my front-end skills are lacking when it comes to searching for solutions.

Apologies in advance if this is a redundant post.

My issue is that I have a container that is 980 pixels wide, and I want to fill it with smaller divs that are 180 pixels wide. I have 7 smaller divs in total, so ideally, I would like 2 rows with 20 pixels between each div. The first row should have 5 divs, and the second should have 2.

I've tried floating the divs left and adding a margin, but this results in the total width exceeding 980 pixels, causing the layout to break.

I attempted setting a negative right margin on the container, but that didn't yield the desired result.

Any help or links to resources would be greatly appreciated!

EDIT: I should clarify that the container will be resizable, so the smaller divs should adapt to fill the available space, with the first div starting at 0px from the left and the last div ending at 0px from the right. The divs in between should adjust accordingly. I've only come across solutions for single-row layouts, so any advice on multi-row layouts would be helpful. Additionally, it would be ideal if the layout automatically wrapped to the next line if the margins between the smaller divs are less than 1 pixel.

EDIT 2: I've created a jsfiddle to illustrate my issue. The goal is for the green boxes to autofill the gray area horizontally, with a set vertical margin (e.g., 15/20 px).

http://jsfiddle.net/yfnpv/

Answer №1

It seems there may be some confusion about your needs.

If I grasp the idea correctly, it might be this.

demonstration

I have included additional assisting elements :

    ....
    <div class="obj">7</div>
    <div class="obj push"></div>
    <div class="obj push"></div>
    <div class="pushend"></div>
</div>

and the CSS code is :

#container {
    max-width: 980px;
    background-color: gray;
    display: inline-block;
    text-align: justify;
}

.obj {
    width: 180px;
    height: 180px;
    background-color: green;
    display: inline-block;
}
.obj.push {
    height: 0px
}
.pushend {
    width: 100%;
    height: 0px;
    display: inline-block;
}

The concept is not my own, but I can't recall the exact source.

I suspect the original creator utilized some clever techniques with pseudo-elements to avoid altering the HTML, although I cannot recollect it precisely.

Answer №2

<div id="container">
   <div class="1column first">one column</div>
   <div class="1column">one column</div>
   <div class="1column">one column</div>
   <div class="1column last">one column</div>
<div class="clear"></div>
   <div class="1column first">one column</div>
   <div class="1column">one column</div>
   <div class="1column">one column</div>
   <div class="1column last">one column</div>
</div> <!-- container -->

The Cascading Style Sheets

#container {width: 630px;}
.1column {width: 150px; float: left; margin-left: 5px; margin-right: 5px;}
.first {margin-left: 0px;} 
.last {margin-right: 0px;}
.clear {clear:both;}

To ensure proper alignment, you need to calculate the total width of each div by adding the width and margin values together. For instance, the first div should be 155px (150px + 5px), the next should be 160px (150px + 5px + 5px). By setting the first and last divs to 155px and the others to 160px, the total width becomes 630px. To move to the next row, insert a clear:both div between the divs to clear floats. Repeat this process as needed.

The 5px margins create a 10px gap between each div (5px + 5px).

This is a basic example. You can explore CSS grid frameworks for more advanced setups. Ensure that the inner divs stay within the width of the "container" div to avoid issues. Remember, padding + margin + width + borders = total width. Adding a 1px border will increase the width by 2px (1px on each side).

Additionally, to center align the entire layout, include the following in the container div's CSS:

#container {width: 630px; margin-left: auto; margin-right: auto;}

I trust this information proves useful.

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

Resizing an image within a div with automatic adjustment, centered and aligned to the bottom position

I'm really struggling to understand this concept and not making much progress. I have a background image that automatically scales to fit the window size. In front of it, I want to center an image fixed to the bottom of the page, while still being sca ...

Disappear solely upon clicking on the menu

Currently, I am working on implementing navigation for menu items. The functionality I want to achieve is that when a user hovers over a menu item, it extends, and when they move the mouse away, it retracts. I have been able to make the menu stay in the ex ...

Tips for resolving the issue of windows resizing due to off-screen elementsplacement:

During the development of a project, I wanted to incorporate an effect into my webpage. To achieve this, I positioned elements off the screen. However, upon running the code, the window resized with scrollbars, causing inconvenience for mobile users Below ...

Adjusting the height of a textarea within a table

My textarea's height is supposed to be 500%, but it's not changing. I suspect that being inside a table might have something to do with the issue, but I'm unsure of what needs to be adjusted to set the height correctly. Surprisingly, the wid ...

In my current Next.js project, I tried setting up a new [collectionId].jsx file within the pages directory, but I am facing issues with getting

In my current next.js project, I recently created a file named [collectionId].jsx within the pages directory. Interestingly, I noticed that Tailwind CSS does not seem to work properly with this file. However, when I renamed the file to [collectionId].js wi ...

What is the best way to arrange elements above and below each other in a single flexbox container?

Currently, I am facing a challenge aligning the number 238,741 and the letter N in Number. There is a padding between the Prize Pool div and the Number Active div. All of these elements are enclosed within a parent container with display set to flex and fl ...

Creating CSS dynamically using PHP

Even after reading numerous blogs and forums, I'm still unable to get this working. My goal is to allow users to personalize their user account style sheet. I made sure to include <?php header("Content-type: text/css"); ?> at the beginning of t ...

Responsive cards using Bootstrap styling

Currently trying my hand at mastering flexbox for responsive design with Bootstrap. In the picture, there are 4 cards where 2 should be displayed at the bottom and the other 2 at the top, but on mobile phones, they should all stack at the bottom. I attempt ...

What is the best way to create a flexible grid that automatically adjusts to either two columns or one column depending on the width of the

My challenge lies in arranging items into two columns or one, with a specific layout for mobile devices. The order of the items changes between the two column and single column layouts. The number and size of items vary dynamically. For example, in a tw ...

Get the Bootstrap download that includes CSS files rather than the LESS files

What is the reason behind bootstrap switching to only having LESS files instead of the traditional bootstrap.css file? Is there a way to download the bootstrap framework that includes the CSS files instead of just the LESS files? ...

Adjust the <h1> tag's size using responsive Bootstrap design

Is it possible to adjust the font size of the <h1> tag specifically for small and extra small screens? The default size of the <h1> tag is suitable for medium screens but appears very large on small and extra small screens. I would like to cu ...

What causes the variation in results when I input CSS directly into the head section versus linking it from a separate .css file?

As a beginner, I am facing an issue with my CSS. When I directly insert the CSS into the head of my .html file, everything looks perfect. However, when I link my .css file into the head, the very first word ("Holy") does not display properly. I have double ...

Starting the Android System Magnifier with a Click: A Step-by-Step Guide

Is there a way to incorporate a magnifying glass into an HTML page using jQuery or within an Android app? Ideally, it would be for a single picture. In my application, I am displaying an HTML file from my assets in a webview. The HTML page utilizes jQuery ...

My Jquery CSS Checkbox is failing to register when it's checked

I have implemented custom checkboxes using a custom CSS checkbox generator. $( ".button" ).click(function() { if(document.getElementById('terms_checkbox').checked) { alert('Checkbox is checked'); } else { alert('Chec ...

Make the element switch from hidden to visible when hovering over it using CSS

I had a challenge to only show some rating text on my website when I hovered over it. Being new to coding with CSS and JavaScript, I was experimenting with overriding styles using the Stylebot extension in Chrome. I encountered an issue while trying to mo ...

Is it possible to choose only half of the elements using the :nth-child selector in

Consider this code snippet: <ul> <li>Hello Universe</li> <li>Hello Universe</li> <li>Hello Universe</li> <li>Hello Universe</li> </ul> Can we select exactly half of the total elements by ...

Creating a unique chrome extension that swaps out HTML and JavaScript components

Is there a possibility to create a Chrome extension that eliminates the JavaScript and CSS from a website while it loads, replacing them with new scripts from a separate source? For example, changing 'Old script' to 'new script', or &a ...

Modify the text color of all input elements with Tailwind

I have been using this code in multiple sections of the app: <label className="input text-neutral-content"> Name <input type="text" className="grow text-base-content"/> </label> While I understand that ...

Customizing Row Background Color in Bootstrap

Currently working on a project www.codepen.io/anon/pen/yMmjZb The problem I am facing is with my 3rd row (the one with the 3 columns) where the background color is bleeding beyond the intended boundary. My suspicion is that it's due to the row span ...

The offspring elements are positioned outside of the main footer element

There seems to be an issue with my <footer>. All child elements of the <footer> are appearing outside of it. Does anyone know how I can properly place child elements inside the <footer> and align them from left to right? footer{ bac ...