Home > Net >  best way to implement css 100% width by ignoring parent div padding
best way to implement css 100% width by ignoring parent div padding

Time:11-27

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 >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></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*/
}

rough diagram of what I exactly meanenter image description here

CodePudding user response:

  • If you wish to be more dynamic, then use of css variable will make your code effective
  • we use --padding variable here. to change values of variable, just change it in :root.
  • I have used a 1px border to show difference(black is parent,red is children)
  • The formula i used for width is,
    total possible length when not parent padding is ignored twice the padding(becuase padding acts on both side) - 1px(which is border)
    and for margin is -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 >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

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.

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 >
      <div >My content 1</div>
      <div >My content 2</div>
      <div >My content 3</div>
      <div >My content 4</div>
      <div >My content 5</div>
      <div >My content 6</div>
</div>

  • Related