Position:Fixed not working

Hello guys, I’ve just started Web development course on FCC, I also decided it would be a good idea to also build a small website of my own, I’m feeling pretty stupid but actually took me two hours to build something which would normally take maybe few minutes and now I’m stuck, I want to make my menu bar fixed, so whenever user scrolls down, it follows, but whenever I use the position:fixed, whole website breaks apart.
HTML

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="theme.css">
        <title>Project NSM</title>
    </head>
    
    
    

    <body>
        <ul id="menubar">
            <a href="index.html" class="menuitem"><li>Main</li></a>
            <a href="#" class="menuitem"><li>Tutorial</li></a>
            <a href="#" class="menuitem"><li>Books</li></a> 
            <a href="#" class="menuitem"><li>Exercises</li></a> 
            <a href="#" class="menuitem"><li>Contact</li></a> 
        </ul>
    </body>





</html>

CSS

body
{

    background-color:#28262C;
}
#menubar{   
    margin:0px;
    padding:0px;
    list-style-type: none;
    background-color: #D4C2FC;
    height: 40px;
}
#menubar  li {
    padding-top:10px;
    font-family:Arial;
    height:40px;
    text-decoration:none;
    font-weight:bold;
    color:black;
    margin-left:25px;
    float:left;
    font-size:15px;

}
#menubar li a {
    text-decoration: none;
}
#menubar a li:hover{
    font-family:Helvetica;
    height:30px;
    color: cornsilk;
    font-weight:bold;
    background-color:#998FC7;
    font-size:17px;
    opacity: 0.9;
}

Hey,

Try this:

#menubar{   
    margin:0px;
    padding:0px;
    list-style-type: none;
    background-color: #D4C2FC;
    height: 40px;
    width:100%;
    position:fixed;
}

Added width to the navbar of 100% fixed the issue for me.

Works nice, thanks.
But why was it breaking?

I’m the student just like you, so I might be wrong but I believe because since it had no size set around the lists. It would break just because it’s a sticky menu and basically is floating on top of other elements.

Happy coding! :slight_smile:

It’s not breaking. That’s what happens.
An <li> element is a block level element. Block elements generally fill the entire width of the container block. It seems that when position:fixed is used, block level elements behave more like inline-block elements, which only occupy as much horizontal space they need.

You can apply CSS background colours or borders to elements so you can see their extents.

Have read of these MDN articles: