For the following DOM, only child3 should be having a 100% width ignoring/overriding the padding of the parent container, and the rest child elements should have 100% width while also respecting the padding
<div class="container">
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
<div class="child4"></div>
<div class="child5"></div>
<div class="child6"></div>
</div>
constraints for container's CSS
.container {
width: 300px;
padding: 40px;
}
what is the best way to implement the same? one way to achieve this is:
.child3 {
width: 300px;
margin-left: -40px; /*to offset parent container's padding*/
}
Here is what my code does:
.container { width: 300px; padding: 40px; }.child3 { width: 300px; margin-left: -40px; /*to offset parent container's padding*/ }
<div class="container"> <div class="child1"></div> <div class="child2"></div> <div class="child3"></div> <div class="child4"></div> <div class="child5"></div> <div class="child6"></div> </div>
--padding
variable here. to change values of variable, just change it in :root
.total possible length when not parent padding is ignored + twice the padding(becuase padding acts on both side) - 1px(which is border)
-padding
The code snippet:
:root { --padding: 40px; }.container { width: 300px; padding: var(--padding); height: 100px; border: 1px solid black; }.child3 { width: calc(100% + (2*var(--padding)) - 1px); margin-left: calc(0px - var(--padding)); /*to offset parent container's padding*/ }.container *{ border: 1px solid red; height:5px; }
<div class="container"> <div class="child1"></div> <div class="child2"></div> <div class="child3"></div> <div class="child4"></div> <div class="child5"></div> <div class="child6"></div> </div>
Another approach is to write it like this (when I see the layout)... Excuse me if I'm wrong because I delete the padding and add margins to the divs instead and match the image you added to your post.
See the momment of @Roko C. Buljan
I don't know if you want to do this, so let me know if it looks OK for You or if I must delete my answer.
It seems less tricky AMO.
*{ box-sizing: border-box; }.container { width: 300px; padding-top: 40px; padding-bottom: 40px; border:1px solid #000000; }.container div{ margin-left: 40px; margin-right: 40px; margin-bottom: 10px; height:20px; border:1px solid #000000; }.container.child3 { width: 100%; margin-left:auto; margin-right:auto; border:1px solid #ff0000; }.container.child6 { margin-bottom: 0px; }
<div class="container"> <div class="child1">My content 1</div> <div class="child2">My content 2</div> <div class="child3">My content 3</div> <div class="child4">My content 4</div> <div class="child5">My content 5</div> <div class="child6">My content 6 (last div)</div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.