i’m trying to create a centered navigation bar with a 10px border top, left and right. but when i change the width it’s stuck to the left of the page. if i put a margin they don’t look evenly spaced. very new to this.
here’s my current css
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>my name</title>
<link href="normalize.css" rel="stylesheet">
<style>
@import url('https://fonts.googleapis.com/css2?family=Work+Sans&display=swap');
body {
background-image: linear-gradient(60deg, #abecd6 0%, #fbed96 100%);
box-sizing:border-box;
nav {
display: inline-block;
background-color: #381D2A;
justify-content: center;
position: fixed;
width: 99%;
z-index: 1;
border-radius: 20px;
margin: auto;
padding: 0;
margin: 10px 10px 0 10px;
}
nav ul {
display: flex;
align-items: center;
padding: 0;
list-style: none;
justify-content: center;
}
</style>
</head>
<body>
<nav>
<ul>
<li><a href="#about-me">about me</a></li>
<li><a href="#projects">projects</a></li>
<li><a href="#contact me">contact me</a></li>
</ul>
</nav>
4
Answers
Make the width of the
nav
element take100%
that way it is evenly distributed, and just add increase/decrease themargin
as you see fit.Also, make sure you have
box-sizing
set toborder-box
to tell the browser to account for any border and padding in the values you specify for an element’s width and height (docs)Edit: I now saw that you using
postion: fixed
. Then the element is removed from the normal document flow, and is postioned with top, right, bottom and left property. So to get your desired layout you have to add:The calc in width property is calculating the width (in your case 100%) minus the value in left and right property, so you get your desired "margins".
I think you need to add
box-sizing: border-box
to body element:The box-sizing property is adjusting the width/height when you add margin/padding. More info:
https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing
If you need to use "position: fixed;", then you need to position it with "left/right" in order to make it center not margin left/right.
Edit:
Following your code example, I would do something like this
You need to understand positioning and how it works.
What I did in my code snippet: