Search code examples
htmlrotationcss-animationstransform

Allow user to flip webpage/section upside down with button?


I'm looking to allow visitors to my website the ability to rotate the webpage upside (180º) with the click of a button.

I know I can go into the CSS and add the following code to completely flip it:

body{
        -moz-transform: rotate(180deg);
        -webkit-transform: rotate(180deg);
        -o-transform: rotate(180deg);
}

But I want to be able to give the user the ability to essentially turn this on/off. Is there a way to do this?

BONUS POINTS if the rotation can be CSS animated to do a smooth transition. But not required.


Solution

  • You can assign an event to a button or link, and on click, the page will flip.

      const button = document.querySelector('.button');
    
      const changeClass = (e) => {
        const body = document.querySelector('.main');
        body.classList.toggle('rotate');
      };
    
      button.addEventListener('click', (e) => {
        changeClass(e);
      });
      body {
        margin: 0;
      }
      .main {
        background: url(https://japan-forward.com/wp-content/uploads/2022/02/Mt-Fuji-Eruption-Volcano-006-scaled.jpg);
        background-size: cover;
        height: 100vh;
      }
      .rotate {
        transform: rotate(180deg);
        -moz-transform: rotate(180deg);
        -webkit-transform: rotate(180deg);
        -o-transform: rotate(180deg);
      }
      .container {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-decoration: none;
        width: 100vw;
      }
      .text {
        color: #ffffff;
        margin-bottom: 5px;
      }
      .button {
        width: 140px;
        height: 100px;
        border-radius: 20px;
        border-width: 0;
        font-family: 'Roboto', sans-serif;
        font-size: 20px;
        background-size: 100%;
        background-color: blue;
        color: #ffffff;
      }
      .footer {
        background: #ff0000;
        width: 100%;
        height: 40px;
        position: absolute;
        bottom: 0;
        text-align: center;
        font-size: 20px;
      }
    <div class="main">
      <div class="container">
        <button class="button">Click to rotate 180</button>
        <footer class="footer">Footer</footer>
      </div>
    </div>