How to Make Full-Width Items in a Container with Padding in CSS?

I'm trying to create a layout where blue and green rectangles (background-color) take the full width of the screen while the text should keeping a padding inside the container. Here is my HTML and CSS code: https://jsfiddle.net/6hyo07mb/1/ The problem is that the rectangles elements are not taking the full width of the container because of the padding. How can I make these items take the full width of the screen while keeping the container's padding? <div class="container"> <div class="item">Section 1</div> <div class="item">Section 2</div> <div class="item">Section 3</div> <div class="item">Section 4</div> <div class="item">Section 5</div> </div> html, body { margin: 0; padding: 0; width: 100%; height: 100%; } .container { background-color: red; width: 100%; height: 100%; padding: 0 20px; } .item { width: 100%; height: 20%; } .item:nth-child(odd) { background-color: blue; } .item:nth-child(even) { background-color: green; }
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
7 Replies
Chris Bolson
Chris Bolson•5mo ago
This sounds confusing. You want the container to have padding but at the same time you want its contents, the "item" elements, to take the full width? I might be missing something that sounds rather contradictory 🤔 If you want the text to have padding, just place the padding on the "item" elements.
clevermissfox
clevermissfox•5mo ago
yes just move the padding down to the items not the container and also add a
css *, *::before, *::after {box-sizing: border-box;}
css *, *::before, *::after {box-sizing: border-box;}
so that your padding is included in the width calculation and it doesnt cause overflow;
Abc
AbcOP•5mo ago
If i move the padding down to the items and I want to change the size of padding maybe after a couple months, then I have to do it on all items. Is there not a better solution?
Chris Bolson
Chris Bolson•5mo ago
You only have to add it once to the .item class.
Abc
AbcOP•5mo ago
Not if I use bootstrap: <div class="p-3">Padding on all sides</div>
Chris Bolson
Chris Bolson•5mo ago
I'm afraid that I don't know Bootstrap but presumably you can add the class to the parent with a child selector. I realize that it is not the same, but in Tailwind this can be done by just adding *:p-3 to the parent element. Maybe something similar is possible in Bootstrap After a quick search on Bootstrap it seems that this isn't possible, that is to say be defining a child class on the parent element, so your only option is to define it in the style sheet itself.
clevermissfox
clevermissfox•5mo ago
In your style sheet you have .container{padding : 0 20px;} just move it down a couple lines to .item {padding : 0 20px;}
Want results from more Discord servers?
Add your server