Theodore Steiner
Theodore Steiner

Reputation: 1605

Responsive Flex Menu

I've created a responsive menu with a simple trigger using flexbox, but I've run into a problem. Within one of the media queries, I drop the UL down below the div that contains the logo and the trigger and changed it's display:none until the trigger is clicked.

When I was trying to style UL for it's open state, when I gave it margin and padding, it increased the overall size of the nav so you could tell something was hiding. Since the element is hidden, shouldn't the margin and padding have no effect until the open state is triggered?

I found a work around by adding margin and padding to the LI but I feel like that's a cheat.

$(function() {
	
	$('.trigger').click(function() {
		$('.mainNav').toggleClass('show');
	});
	
	
});
* {
	margin: 0;
	padding: 0;
	list-style-type: none;
}

body {
	font-size: 17px;
	color: white;
}

nav {
	height: 100%;
	width: 100%;
	background-color: #333;
}

.nav-fixedWidth {
	height: inherit;
	min-height: 70px;
	width: 960px;
	margin: 0 auto;
	display: flex;
	flex-flow: row;
}

.logo-and-trigger {
	display: flex;
	justify-content: space-between;
}

.logo {
	content: '';
	height: 50px;
	width: 50px;
	background-color: #f1f1f1;
	position: relative;
	margin: 8px 0;
}

.trigger {
	content: '';
	height: 50px;
	width: 50px;
	background-color: #f1f1f1;
	display: none;
	position: relative;
	margin: 8px 0;
}

.mainNav{
	display: flex;
	width: 200px;
	justify-content: space-between;
	margin: 20px 0px;
	margin-left: auto;
	overflow: hidden;
	transition:max-height .3s ease;
}

@media screen and (max-width: 960px) {
	
	.nav-fixedWidth {
		width: 100vw;
	}
}

@media screen and (max-width: 900px) {
	
	.nav-fixedWidth {
		flex-flow: column;	
	}
	
	.mainNav {
		margin:0;
		width: 100%;
		display: block;
		max-height: 0;
	}
	
	.mainNav li {
		margin: 20px;
		padding: 20px;
		margin-left: 0;
		width: 100%;
		padding-left: 0;
	}
	
	.show {
		max-height: 20em;
	}
	
	.trigger {
		display: flex;
	}
	
	
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
	<div class="nav-fixedWidth">
		<div class="logo-and-trigger">
			<div class="logo"></div>
			<div class="trigger"></div>
		</div>
		<ul class="mainNav">
			<li>Link 1</li>
			<li>Link 2</li>
			<li>Link 3</li>
		</ul>
	</div>
</nav>

Upvotes: 0

Views: 365

Answers (1)

sophie
sophie

Reputation: 166

I think when you use "$('.mainNav').toggleClass('show');", you don't change UL to display:none so a space is allocated for UL on the page even if the trigger is not clicked. That's why you can see margin and padding on UL element.

If you want to keep toggleClass, you can apply margin and padding on the CSS class .show

Or if you want to add margin and padding on UL, you have to use $('.mainNav').css({'display':'block'}) and $('.mainNav').css({'display':'none'}) and don't use toggleClass.

Upvotes: 1

Related Questions