简体   繁体   中英

How to prevent cutting off absolute positioned elements and still keep a box-shadow embrace the parent div?

First of all an example: https://jsfiddle.net/85uqehz5/

The code is just an example, an easier version of my real code. I figured out that I cant't have both: Setting the wrap-div to overflow: visible the menu that shows up isn't cut off but the box shadow doesn't embrace the box; With overflow:auto; the box-shadow is working but the menu cut off. How could I solve this? A fixed height would not be an option.

Example Code:

 $('#menu').click(function() { $('#menu-list').toggleClass('hidden'); }); 
 #wrap { width: 80%; height: auto; overflow: visible; box-shadow: 0 0 .2rem rgba(0, 0, 0, .4); } #content { width: 200px; height: 20px; margin: 0 auto; } #content2 { float: left; } .hidden { display: none; } #menu { position: relative; height: 20px; width: 100px; background-color: #ccc; float: left; } #menu-list { position: absolute; top: 20px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="wrap"> <div id="content"> Some Content </div> <div id="content2"> Some Content </div> <div id="menu"> Open Menu <div id="menu-list" class="hidden"> <div> bla </div> <div> bla </div> <div> bla </div> </div> </div> </div> 

It's very simple, in your specific case:

1- Remove overflow: auto; from #wrap

2- Add this to your CSS :

#wrap:after {
  display: table;
  content: "";
  clear: both;
}

This makes the height of #wrap 's calculation include the floated element.

If you have multiple uses declare a class like clearfix and use it whenever needed.

Demo: https://jsfiddle.net/85uqehz5/1/

Floats must be cleared: https://jsfiddle.net/85uqehz5/3/

<div id="wrap" class="clearfix">

The reason the menu is cut off is because you haven't clear your float: left and that is done with such piece of code to the container

.clearfix:after {
    content: "\0020";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

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