Blend divs that have a width specified in percentages with a margin measured in pixels

My challenge is creating a page layout where multiple items each have a 33.33% width to fill the entire page, with a desired 20px margin between them. However, adding this margin only on the right of every 1st and 2nd item in a row causes layout issues. You can view the problem by removing the commented-out CSS in the provided JSFiddle link.

JSfiddle

The question at hand is: How can I achieve a consistent 20px margin while keeping all .item divs the same size? Simply adjusting the percentage width or incorporating the removed width of an .item as margin won't provide a stable 20px due to the nature of percentages.

HTML

<div id="main">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
    <div class="item">10</div>
    <div class="item">11</div>
    <div class="item">12</div>
</div>

CSS

#main .item {
    height: 100px;
    width:33.33%;
    float:left;
    text-align: center;
}
#main .item:nth-child(3n+1) {
    background: red;
}
#main .item:nth-child(3n+3) {
    background: yellow;
}
#main .item:nth-child(3n+2) {
    background:lightblue;
}
/*.item:nth-child(3n+1), .item:nth-child(3n+2) {
    margin-right: 20px !important;
}*/

Answer №1

To subtract the 20px from the 33.33%, you can utilize the calc() function.

An example of this would be setting the width to calc(33.33% - 20px) in order to adjust the margins accordingly.

Take a look at the Updated Example for reference.

#main .item:nth-child(3n+1),
#main .item:nth-child(3n+2) {
    width: calc(33.33% - 20px);
    margin-right: 20px;
}

However, using this method may result in elements with varying widths due to not subtracting the 20px from all elements. A more effective approach would involve subtracting 13.33px from each element (40px/3px):

Check out the Updated Example to see how this alternative solution works.

#main .item {
    height: 100px;
    width: calc(33.33% - 13.33px);
    float:left;
    text-align: center;
}

Answer №2

Adjust the dimensions of each element with the .item class by using the calc() function.

#container .item {
    height: 100px;
    width:calc(33.33% - 20px);
    float:left;
    text-align: center;
}

Link to code example

Answer №3

Utilize the % symbol for wrapping and adjust margin to padding while incorporating box-sizing: border-box

.wrapper {
  /* allow for adding padding to width */
  box-sizing: border-box;
  width: 33.33%;
  float: left;
  padding: 20px;
  background-color: #EFEFEF;
}
.item {
  background-color: #ddd;
  padding: 5px;
}
<div class="wrapper">
  <div class="item">Some text here</div>
</div>
<div class="wrapper">
  <div class="item">Some text here</div>
</div>
<div class="wrapper">
  <div class="item">Some text here</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

Python Selenium: How to interact with an element nested within multiple HTML tags

Currently, I am working on automating a website using selenium webdriver in Python. However, I have encountered an issue when trying to click on a specific tag. The website that I am attempting to automate is quite old and contains numerous iframes and &l ...

styled-components: expand designs and alter type of element

Imagine I have these specific styles: color: black; border: 1px solid white; and now I want to apply them to two different elements: const SomeImg = styled.img` margin: 2em; `; const SomeDiv = styled.div` margin: 3em; `; How can I make sure that b ...

What is the best way to dynamically select and deselect radio buttons based on a list of values provided by the controller?

I am currently working on implementing an edit functionality. When the user initially selects a list of radio buttons during the create process, I store them in a table as a CSV string. Now, during the edit functionality, I retrieve this list as a CSV stri ...

Tips for effectively showcasing a span class field

Can someone help me with an issue I am having in Chrome browser where I am trying to display two "text text-pass" from HTML to my print console but it is not working? Any advice would be appreciated. Here is my browser HTML code: <a href="/abc/123" ...

Deleting text after an answer has been given using jQuery or JavaScript

I seem to have encountered a problem with the logic I've implemented. The desired functionality is for the user to enter an answer to the question presented. Upon submitting the answer, the current text (first question) should disappear and the next q ...

Trim the data in the following table cell using CSS

I'm trying to create a list using a table structure: https://i.sstatic.net/ucICV.png However, the lengthy URL is causing the table to expand wider than desired. I have attempted solutions like: table { table-layout: fixed; width: 100%; } and td.t ...

The mousedown functionality does not seem to be functioning properly on elements added dynamically

How can we trigger the mousedown event on dynamically appended elements? $(function() { var isMouseDown = false, isHighlighted; $("#myTable tr").mousedown(function() { isMouseDown = true; $(this).toggleClass("highlighted"); isH ...

Utilizing Z-index for the arrangement of DIVs and elements in a webpage

I am facing an issue with my website design where the content section overlaps with the banner. This causes the content section to be hidden behind the banner, and I need it brought to the front. The problem specifically lies with the search element on my ...

Incorporating a variety of images into this hexagonal design framework

Hello there! I am just starting to learn CSS and HTML, and I have a question. Is it possible for me to use the same CSS styling but have different images inside each of the hexagons? I want to replace the image '' with multiple images without rep ...

PHP isn't sending data (even though the name tag is defined)

After reviewing numerous posts where individuals forget to include the name attribute in their input tags, I came up with a simple script: <form action="submit_form.php" method="post"> Name: <input type="text" name="name"><br> ...

Display the HTML element prior to initiating the synchronous AJAX request

I'm looking to display a <div> upon clicking submit before triggering $.ajax() Here's my HTML: <div id="waiting_div"></div> This is the CSS: #waiting_div { position: fixed; top: 0px; left: 0px; height: 100%; ...

Creating a visual that when clicked, reveals an enlarged version at a different location

Is there a way to make an image appear in a different location on the page when it's hovered over? I've searched online but couldn't find a solution using just HTML and CSS. Does anyone know how to achieve this effect? Image not hovered: ht ...

Java script request via Ajax is failing to execute

Within my HTML code, I have included a button like so: <button type="submit" id="post-form" class="btn btn-primary" onclick="send()">Send</button> Accompanying this is the JavaScript function send() : fu ...

An issue has occurred due to an illegal mix of collations (greek_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) when performing the operation 'like'

Although this topic has been extensively covered, my issue presents a slightly different challenge. I have set the default charset to utf8 in both the connection made to mysqldb in my Python code and my HTML files. conn = pymysql.connect(host='my ...

When utilizing Xpath, it consistently triggers the Python <li> element as the first child

I am attempting to click on multiple links with the following code: self.browser.find_element_by_xpath("//li[@onclick[contains(text(),"+origin_iata_code+")]]").click() The origing_iata_code is from this list: ['FLL', 'MCO', 'AFL ...

AngularJS Textarea with New Lines after Comma

As a beginner in front-end development, I am exploring different approaches to handling a text area that inserts a new line after each comma. My main focus is on finding the best solution within AngularJs (filter, Regex, etc). Before: hello,how,are,you ...

How can I use AngularJS to show a JSON value in an HTML input without any modifications?

$scope.categories = [ { "advertiser_id": "2", "tier_id": 1, "tier_name": "1", "base_cpm_price": "", "retarget_cpm": "", "gender": "", "location": "", "ageblock1": "", "ageblock2": "", "ageblock3": ...

Showing a JSON array with varying nested lengths in an HTML5 format

I have a JSON string containing nested arrays with elements of unequal lengths. I am looking to display this data on a page using either Javascript or Angular.js. { [ 'id':1, 'value':'tes1' 'nextLevel':[&ap ...

Calculate the total of additional user inputs and show the result in a separate element using JavaScript

Query Is there a way for an element to dynamically show the total of different inputs? Situation I have multiple text boxes all with the same class. There are 4 input fields, each containing a number - Input 1 is "1", Input 2 is "2", and so on. The goal ...

transforming the accordion into a checkbox

https://i.sstatic.net/5y2gv.pngWhile working on my Angular application, I encountered an issue with using the Bootstrap accordion component. I am trying to make the accordion function as a checkbox, where when the checkbox is checked, the accordion expand ...