Home > database >  Scrolling behaviour for single page navbar button in CSS
Scrolling behaviour for single page navbar button in CSS

Time:11-30

I am attempting to create a single page resume using pure HTML/CSS. I'm implementing a navbar such that when clicking a button that links to a div (on the same page), it automatically scrolls down to that section (with the scrolling effect). How can this be done? Thanks.

CodePudding user response:

Hey I mocked up something really simple for you to try out. You can achieve what you are looking for by using <a> tags that link to the id of each element. To get the scroll smooth, just use some CSS scroll-behaviour:smooth.

    <!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>Nav-bar</title>
            <link rel="stylesheet" href="styles.css" />
        </head>
        <body>
            <div class="nav-bar">
                <ul class="nav-link">
                    <a href="#intro">Intro</a>
                </ul>
                <ul class="nav-link">
                    <a href="#work-experience">Work Experience</a>
                </ul>
                <ul class="nav-link">
                    <a href="#education">education</a>
                </ul>
                <ul class="nav-link">
                    <a href="#intrests">intrests</a>
                </ul>
                <ul class="nav-link">
                    <a href="#refrences">refrences</a>
                </ul>
            </div>
            <div class="container">
                <div id="intro" class="section">INTRO</div>
                <div id="work-experience" class="section">WORK EXPERIENCE</div>
                <div id="education" class="section">EDUCATION</div>
                <div id="intrests" class="section">INTERESTS</div>
                <div id="refrences" class="section">REFRENCES</div>
            </div>
        </body>
    </html>

with some css like

    html {
        scroll-behavior: smooth;
    }

    .nav-bar {
        display: flex;
        list-style: none;
        width: 100%;
        background: black;
        color: white;
    }

    .nav-link > a {
        text-decoration: none;
        color: white;
        font-size: 1.5rem;
    }

    .section {
        height: 50vh;
        text-align: center;
        font-size: 3rem;
    }

CodePudding user response:

Just make the href or how you would be opening a link in a normal way to the id of the div, for example; if your code is a link on top (<a></a>) just put an id in (<a href="#divid"></a>) the href. Set scroll-behavior in css to scroll-behavior: smooth; for the smooth scroll on your body or link.

  • Related