DownbeatTax DownbeatTax - 26 days ago 6
CSS Question

Centering DIV inside another DIV

I already tried many of solutions on stackoverflow (

margin:0 auto;
text-align
, ...) and none of them yet worked.

I'm trying to center navigation menu (div) on the middle of navigation bar, but till now I've been unable to do that. I successfully did it with
margin-left:20%
but what this caused is when I minimized window, button fell beneath others and destroys whole webpage.



body{
margin:0;
}

header{
height:2.5vw;
width:100%;
background-color:#2f2f2f;
box-shadow: 0px 5px 5px #111111; /* #888888 */
}
nav{
/* margin-left:20%;
margin-right:20%; */
}
li{
display:flex;
height:2.5vw;
width:20%; /* 33.2% 19.9vw */
float:left;
border-left-color:#000000;
border-left-style:solid;
border-left-width:thin;
border-right-color:#000000;
border-right-style:solid;
border-right-width:thin;
text-align:center;
justify-content: center;
flex-direction:column;
color:#5F5F5F;
font-size:1vw;
}
li:hover{
background-color:#505050;
}
li:first-child{
border-right:none;
}
li:last-child{
border-left:none;
}

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<header><nav><li class=but>Home</li><li class=but>Projects</li><li class=but>Contact</li></nav></header>
</body>
</html>




Answer

You can use CSS Flexbox.

Make your <nav> flexbox like:

nav {
  display: flex;
  justify-content: center;
}

body{
	margin:0;
}

header{
	height:2.5vw;
	width:100%;
	background-color:#2f2f2f;
	box-shadow: 0px 5px 5px #111111;  /* #888888 */
}
nav{
	display: flex;
    justify-content: center;
}
li{
	display:flex;
	height:2.5vw;
	width:20%; /* 33.2% 19.9vw */
	float:left;
	border-left-color:#000000;
	border-left-style:solid;
	border-left-width:thin;
	border-right-color:#000000;
	border-right-style:solid;
	border-right-width:thin;
	text-align:center;
	justify-content: center;
	flex-direction:column;
	color:#5F5F5F;
	font-size:1vw;
}
li:hover{
	background-color:#505050;
}
li:first-child{
	border-right:none;
}
li:last-child{
	border-left:none;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<header><nav><li class=but>Home</li><li class=but>Projects</li><li class=but>Contact</li></nav></header>
</body>
</html>

Hope this helps!