Home > database >  Getting an element to "Stretch" past padding of the parent container all the way to the ed
Getting an element to "Stretch" past padding of the parent container all the way to the ed

Time:06-17

If we have elements like this:

<main style="padding: 16px; width: 400px; border: 2px dashed gray;">
        <div style="background-color: gray;">header</div>
        <section>content</section>
 </main>

Is there a way to get the div element to stretch all the way to the edges of the parent past the padding using CSS applied to the div element only?

Someone mentioned using negative margin values for the div, and that could work.

I was hoping there's a way to do it without using values directly, in case the CSS padding applied to the parent container changes.

CodePudding user response:

If you know how much padding is applied to the parent, you can apply negative margin to the child. then (optionally) re-apply padding to the child so your content stay in the original parent's bounds.

.wrapper {
  padding: 16px;
  border: 2px dashed gray;
}

.header {
  background-color: gray;
  margin-left: -16px;
  margin-right: -16px;
  padding-left: 16px;
  padding-right: 16px;
}
<main  style="width: 400px;">
        <div >header</div>
        <section>content</section>
 </main>

CodePudding user response:

can be solved with position: absolute

<main style="padding: 16px; width: 400px; border: 2px dashed gray; position: relative">
        <div style="background-color: gray; position: absolute; left: 0; top: 0; right: 0;">header</div>
        <section>content</section>
 </main>

CodePudding user response:

In case you only want to extend the background, here is an idea using border-image but you need to add overflow:hidden to the parent as well

<main style="padding: 16px; width: 400px; border: 2px dashed gray;overflow:hidden">
        <div style="border-image:conic-gradient(gray 0 0) fill 0//100vw 100vw 0 100vw;">header</div>
        <section>content</section>
 </main>

  • Related