Creating a CSS Grid with Full-Width Columns and Consistent Margins

Currently, I am attempting to create a responsive grid with 4 columns that expands to the entire width of the screen on desktop displays. However, when I introduce margins to space them out evenly, I encounter an issue where the last column either doesn't fill the remaining space or drops down to a new row due to the column widths.

CSS:

#servicesGrid
{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}

.service
{
width:24.75%;
height:45%;
background:#262626;
display:block;
float:left;
margin:1px;
}

#servicesGrid .service:nth-of-type(1)
{
width:100%;
}

#servicesGrid .service:nth-of-type(2)
{
margin-left:0;
}

#servicesGrid .service:nth-of-type(5)
{
margin-right:0;
}

HTML:

<div id="servicesGrid">

    <div class="service"></div>

    <div class="service"></div>

    <div class="service"></div>

    <div class="service"></div>

    <div class="service"></div>

</div>

Check out the example on JSFiddle: https://jsfiddle.net/4bw4p3LL/.

Answer №1

When utilizing % for the width, it is recommended to also use % for margins. This ensures that you reach a total of 100%.

The concept here is that 4*colwidth + 3*margins = 100%

Therefore, by applying a margin-right:0.5% to all .col elements except the last one ( nth-of-type(5) ) , you will achieve a width of

100% - 3*0.5% = 98.5% / 4 = 24.625%

where: 100% represents the width of the servicesGrid, 3 is the number of 0.5% margins given to the initial 3 columns, 98.5% denotes the remaining space occupied by the 4 columns, and dividing it by the number of columns provides the width of each column.

#servicesGrid
{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}

.service
{
width:24.625%;
height:45%;
background:#262626;
display:block;
float:left;
margin:1px 0.5% 1px 0;
}

#servicesGrid .service:nth-of-type(5)
{
margin-right:0;
}
<div id="servicesGrid">

<div id="serviceWide" class="service col" style="width:100%; margin:0 0 1px 0">
</div>

<div class="service col"></div>

<div class="service col"></div>

<div class="service col"></div>

<div class="service col"></div>

</div>

Answer №2

Utilizing the calc function for setting the width can be quite handy. This method allows you to subtract a specific value (such as margin) from the overall width. It's important to note the browser support, which is generally favorable across modern browsers.

Check out this example on jsfiddle

.service {    
    width: calc(24.75% - 1px);
    height: 45%;
    background: #262626;
    display: block;
    float: left;
    margin: 1px;
}

Answer №3

#servicesGrid
{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}

.service
{
 width:calc(24.75% - 1px);
height:45%;
background:#262626;
display:block;
float:left;
margin:1px;
}

#servicesGrid .service:nth-of-type(2)
{
margin-left:0;
}

#servicesGrid .service:nth-of-type(5)
{
margin-right:0;
}
<div id="servicesGrid">
  <div id="serviceWide" class="service col" style="width:100%; margin:0 0 1px 0"></div>
<div class="service col"></div>
<div class="service col"></div>
<div class="service col"></div>
<div class="service col"></div>
</div>

Answer №4

When working with a fixed 1px margin, it can be challenging to set a dynamic width without some exceptions, unless you opt for using <table>.

To tackle this issue, I suggest using width: calc(25% - Ypx) on your columns as a solution that is supported across most browsers (http://caniuse.com/#search=calc). Here's an example of how this can be implemented:

.service
{
    width: calc(25% - 2px);
    height: 45%;
    background: #262626;
    display: block;
    float: left;
    margin: 1px;
}

#servicesGrid .service:nth-of-type(2)
{
    margin-left: 0;
    width: calc(25% - 1px);
}

#servicesGrid .service:nth-of-type(5)
{
    margin-right: 0;
    width: calc(25% - 1px);
}

Answer №5

Another approach is to create the illusion of space between elements using a border, and then utilize box-sizing to factor the border into the element's width. Give this code snippet a try:

#servicesGrid {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.service {
  width: 25%;
  height: 45%;
  background: #262626;
  display: block;
  float: left;
  box-sizing: border-box;
}
.service:nth-child(n+3) {
   border-left: 1px solid white;
}
<div id="servicesGrid">
  <div id="serviceWide" class="service col" style="width:100%; margin:0 0 1px 0"></div>
  <div class="service col"></div>
  <div class="service col"></div>
  <div class="service col"></div>
  <div class="service col"></div>
</div>


Alternate Solution

If you have the option to employ Flexbox, consider implementing the following code:

#servicesGrid {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display:flex;
  flex-wrap: wrap;
  align-content:flex-start;
  align-items:justyfy-content;
  justify-content: space-between;
}
#serviceWide {
  flex:0 1 100%;
  margin-bottom:1px;
}
.service {
  width: 24.8%;
  height: 45%;
  background: #262626;
}
<div id="servicesGrid">
  <div id="serviceWide" class="service col"></div>
  <div class="service col"></div>
  <div class="service col"></div>
  <div class="service col"></div>
  <div class="service col"></div>
</div>

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

What is the best way to include personalized attributes in a form_for?

Here is the code I am working with: <%= form_for @quiz do |f|%> <% @questions.shuffle.each do |q| %> # get_answers returns an array of 4 random answers <% answers = q.get_answers %> <%= f.label q.inquest %><br> ...

Issues with ontimeupdate event not triggering in Chrome for HTML5 audio files

After creating an HTML5 audio element and setting a listener for when its time updates, I have run into an issue where the ontimeupdate function does not fire in Chrome, including Chrome on Android. The audio plays without any issues in other browsers. va ...

Achieve consistent column heights with flexbox styling

I have a solution for achieving equal height columns using the CSS property display:table. Here is an example: .row { display: table; width: 100%; } .col{ display: table-cell; } However, in my case, I am using flexbox and the row class has ...

Positioning an individual element to the right side of the navigation bar in Bootstrap 5

I've been attempting to shift a single nav-item to the right side of the navbar, but I'm having trouble. My navbar is fairly basic, without a search tool or dropdown menu, as seen below: <nav class="navbar navbar-expand-lg bg-body-tertiar ...

What are the implications of storing data on the browser in the form of a JavaScript array?

Below is the code I have written: var back_arr = [], forward_arr = [], i = 1; $('button').on('click', function(){ var new_value = $('input').val(), old_value = $('.content').html(); i = i + 1; ...

Conditionals causing issue with React Button disabled property functionality

Having a DIV with two child elements, namely buttons that should be disabled under certain conditions. Despite correct conditions being applied, the buttons remain enabled which is causing confusion. The code snippet in question is as below : < di ...

Tips on dynamically looping the formcontrolname and implementing validation strategies

Looking for a way to validate multiple looping of dynamic formControlName="xxx" in select field. Check out my HTML code: <ul *ngFor="let detaillist of stressli.stresstabdetails;"> <li> <div class="form-container"> ...

Creating a HTML5 canvas animation of an emoticon winking to add a fun touch to your

Currently, I am facing a challenge in animating an emoticon that was initially sketched on canvas. While following a tutorial to implement draw and clear animations using frames, I haven't been able to achieve the desired outcome. With 6 frames of the ...

Dynamic class name changes in Angular.js based on JSON object

I am trying to dynamically change the class of an <li> element based on the category value I am getting, but for some reason the class name won't update. Here is the code snippet: <div id="content"> <ul id="container" ng-controller ...

What is the best way to assign a jQuery variable to a PHP variable?

After spending some time searching and working on it, I still can't figure out the answer to this straightforward question. Here is the code I have been struggling with. <script> function calculate() { var total = (parseInt($('#stude ...

Altering the text and functionality of buttons with jQuery

A JavaScript method I have is designed to change based on the state of a button, which is determined by using indexOf("..some text.."). $('#add1').click(function(){ if($(this).text().indexOf("Add Me!")) { $.ajax({ type: & ...

Real-time update of quiz results based on varying factors

In my quiz, I have set up variables that start at 0 and increase based on certain conditions. One variable should increase when a question is answered correctly, while the other should increase when a question is answered incorrectly. If you answer a quest ...

NextJS - Fullcalendar is experiencing issues with loading its style completely

I'm currently working on integrating FullCalendar into a Next.js 13 project (T3 Stack) and facing an issue where the style fails to load properly upon navigating back to the page containing my FullCalendar component for the second time. What I'v ...

div or paragraph element nested within a flex container

How can I make the logo text div tag, called Title, take up its content space inside the parent flexbox without wrapping? I prefer not to set the Title div to 100% or use white-space: nowrap. I simply want it to behave like a regular div where it fills it ...

Tips for adjusting the width of Material UI TextField within a Table

I am utilizing a Material UI Table. This is how I construct it: tableValues.map((curRow, row) => { tableRows.push( <TableRow key={this.state.key + "_row_" + row}> {curRow.map((cellContent, col) => { let adHocProps ...

Is it possible to modify the page contents using the htaccess file?

Is there a way to manipulate the content of a page using the htaccess file? Perhaps something similar to a redirect, but instead of directing the user to a new page, it would alter the existing page's content? ...

Creating a CSS animation to slide a div outside of its container is

I currently have a flexbox set up with two adjacent divs labeled as DIV 1 and DIV 2. By default, both DIV 1 and DIV 2 are visible. DIV 2 has a fixed width, occupying around 40% of the container's width. DIV 1 dynamically adjusts its width to ac ...

Arranging elements on a webpage using CSS grid placements

Currently experimenting with css grid, envisioning a scenario where I have a 2x2 grid layout. When there are 4 child elements present, they would form 2 rows of 2 elements each. My challenge is when dealing with an odd number of children, I aim to avoid al ...

Click on a button to send the React Router path as a parameter in

I've got a React form with a submission button like this: <Link className="btn btn-secondary btn-width-200 search-submit" to={{pathname: '/booking/search', query: this.state.filters}}> Search </Link> Within the ...

In HTML, adjust column widths for multiple tables according to the widest column present in any of them

With Python, I am creating an HTML page that contains multiple tables with the same number of columns, all holding the same type of data. While the generated page is functional, I would like to improve readability by ensuring that all tables have the same ...