Mark
Mark

Reputation: 3118

prevent padding background-color from overflowing into child element

I've googled this a lot but I can't find an answer there or here on SO. I need to figure out how to prevent padding background-color from overflowing into its child element. The child element can't move out of its place.

I've tried overflow:hidden, z-index, and pretty much everything.

It's definitely easiest to just see the jsfiddle: https://jsfiddle.net/so23hbf0/3/

HTML:

<div class="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<div class="dropdown">
    <a href="#" class="dropbtn">Books & Media</a>
    <div class="dropdown-content">
        <div class="header">
            <h2>Mega Menu</h2>
        </div>   
    </div>
</div> 

CSS:

.navbar {
    overflow: hidden;
    background-color: yellow;
 }

.navbar a {
    padding: 2rem 1.6rem;
  overflow: hidden;
}

.dropdown {
    overflow: hidden;
    display: inline;
}

.navbar a:hover {
    background-color: black;
}

.dropdown-content {
    background-color: gray;
}

Notice how when you hover the links, the black background spills over into the gray "Mega Menu" area. But it doesn't spill up over the top. I want to prevent it spilling over downwards.

Upvotes: 0

Views: 633

Answers (2)

Michael
Michael

Reputation: 1

.navbar {
	overflow: hidden;
  background-color: yellow;
}

.navbar a {
	padding: 2rem 1.6rem;
  overflow: hidden;
}

.dropdown {
	overflow: hidden;
	display: inline;
}

.navbar a:hover {
	background-color: black;
}

.dropdown-content {
	background-color: gray;
}

div.dropdown{
    /* ... */
    position: relative; 
    z-index: 1;
}
<!--Change Html to:-->

<div class="navbar">
	<a href="#home">Home</a>
	<a href="#news">News</a>
  <a href="#" class="dropbtn">Books & Media</a>
	<div class="dropdown">
		<div class="dropdown-content">
			<div class="header">
				<h2>Mega Menu</h2>
			</div>	 
		</div>
	</div> 
</div>

Upvotes: 0

Adrift
Adrift

Reputation: 59799

Position div.dropdown so you can use z-index to control the stack order in relation to surrounding elements, preventing the menu from overlapping.

Only elements that have a position value other than the initial - static - can have their stacking context re-arranged with z-index see MDN for examples.

div.dropdown {
    /* ... */
    position: relative; 
    z-index: 1;
}

For example: https://jsfiddle.net/0mczuLsx/

Upvotes: 1

Related Questions