简体   繁体   中英

CSS force div with absolute position be behind div with static position

So lets say that I have some document

  #a{width: 10px; height: 10px; background: red; z-index: 10;} #b{width: 100%; height: 100%; background: black; z-index: 5; position: absolute;} 
  <body> <div id="a">foo</div> <div id="b">bar</div> <body> 

The #b div covers the #a , because #b has absolute position.

How can I force #b be behind #a without changing #a position?

您可以添加position: relative对于#a元素的position: relative

You have to set a position other than static to your first div to apply styles like z-index

 #a { width: 100px; height: 100px; background: red; z-index: 10; position: relative; } #b { width: 100%; height: 100%; background: black; z-index: 5; position: absolute; left:0; top:0; } 
 <div id="a">foo</div> <div id="b">bar</div> 

You should add a relative position to your first div :

<body>
    <div id="a">foo</div>
    <div id="b">bar</div>
<body>
<style>
    #a{width: 10px; height: 10px; background: red; z-index: 10; position:relative}
    #b{width: 100%; height: 100%; background: black; z-index: 5; position: absolute;}
</style>

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.

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