简体   繁体   English

有没有办法让子div的背景扩展到父div之外?

[英]Is there a way to have a child div's background expand outside of parent div?

<div id = 1>
   <div id = 2>
     //I want to expand the background of this div outside of the bounds 
     //of is parent
   </div>
</div>

So I have a div nested inside of another div. 所以我有一个div嵌套在另一个div内。 The parent div is aligned to the center of the screen. 父div与屏幕中心对齐。 I want the child to be able to have a background that takes up the width of the screen without changing the position of the content inside. 我希望孩子能够拥有占据屏幕宽度的背景而不改变内部内容的位置。 What would be the best way to go about doing this? 这样做最好的方法是什么?

You can use a negative margin to accomplish that: 您可以使用负边距来实现:

margin: -20px 0 0 -20px;

Checkout a quick JSFiddle I made: https://jsfiddle.net/qcsra5yg/1/ 查看我制作的快速JSFiddle: https ://jsfiddle.net/qcsra5yg/1/

You can use ::after to achieve this. 您可以使用::after来实现此目的。

html HTML

<div class="parent">
  <div class="child">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Magni, in.</div>
</div>

css CSS

.parent {
  display:flex;
  justify-content:center;
  align-items: center;
  background:rgba(255,255,255, .6);
  width: 200px;
  height: 200px;
  border: 2px solid #fff;
}

.child {
  width: 100px;
  height: 100px;
  position:relative;
}

.child:after {
  z-index:-1;
  content:'';
  position: fixed;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background:red;
}

EXAMPLE

EXAMPLE 2 例2

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

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