简体   繁体   English

仅使用 CSS 让元素“拉伸”过去父容器的填充一直到边缘?

[英]Getting an element to "Stretch" past padding of the parent container all the way to the edges using CSS only?

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?有没有一种方法可以让div元素一直延伸到父元素的边缘,使用仅应用于 div 元素的 CSS 进行填充?

Someone mentioned using negative margin values for the div , and that could work.有人提到对div使用负边距值,这可行。

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.我希望有一种方法可以在不直接使用值的情况下做到这一点,以防应用于父容器的 CSS 填充发生变化。

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 class="wrapper" style="width: 400px;"> <div class="header">header</div> <section>content</section> </main>

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如果您只想扩展背景,这里有一个使用border-image的想法,但您还需要将overflow:hidden添加到父级

 <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>

can be solved with position: absolute可以用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM