Trouble with a responsive menu

I am making a menu for a site the slides out when a button is clicked. The problem is I do not know how to make this responsive. Right now i have:

HTML

    <div id="menu" class="sidenav"> 
        <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> 
    <a href="#">Portraits</a>
        <a href="#">Landscapes</a>
        <a href="#">Bio</a>
        </div>

CSS

/* Menu */
.sidenav {
    height: 100%;
    width: 0;
    /* 0 width - change this with JavaScript */
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: black;
    overflow-x: hidden;
    padding-top: 60px;
    transition: 0.5s;
}

JS

function openNav() {
    document.getElementById("menu").style.width = "150px";
}
function closeNav() {
    document.getElementById("menu").style.width = "0px";
}

Right now the JS will slide the menu out 150px which is not very responsive. What I want to achieve is the JS to slide out to the max-width:100% thus only being as large as the element. I tried function openNav() { document.getElementById("menu").style.maxWidth = "100%"; but I believe this doesn’t work because the CSS defines width: 0px I think I have to modify my JS to remove width, then add maxWidth. Is this right?

Ok so I’m assuming what you want to achieve is openNav() should modify your div’s width responsively to take up the size of the element itself. max-width probably isn’t the way to go, as it defines the absolute maximum of an element. If you define max-width: 100%, you’re saying that an element should take up, at most, all the size it can. Doesn’t really change anything, right?

If you want the element to expand responsively, you can modify the width: 150px itself to a percentage.
, say width: 80%

Alternatively, you could circumvent expanding the element altogether and instead have two functions to slide the navigation in and out of view of the viewport. Personally, I would rather do it this way, as performance wise it’s easier for a browser to move an element than modify it’s shape, but it’s like a matter or microseconds so either way works.

Thank you for your quick response. I did try modifying openNav() to expand width: 20% The results look good on my computer, but not very usable with a phone. (Contents are larger than the div in that instance). how would I slide in/out from the viewport?

Np dude.

First, set the position of the element you want to slide, in this case you already have it in ‘fixed’ so that takes care of that. Second give the element a negative ‘left’ property to point if off screen. When a function is run, modify the ‘left’ property back to 0, and it will reset to its original position. You can even add some transform animation to make it look like the nav is popping out rather than just appearing

That’s perfect, I’ll give that a try. Thanks a million!