Is there a way to implement CSS transitions when hiding elements?

My bootstrap navbar collapses and displays items outside of it. However, when I hide the menu, the overlay div disappears immediately and does not transition smoothly with the menu. How can I apply a transition to the div when hiding the menu?

I've tried various approaches but none of them seem to work as expected. What can I do to ensure that the overlay div transitions smoothly when hiding along with the menu?

For a demo, please refer to this link: https://codesandbox.io/s/d31eo

React (demo):

import React, { Component } from "react";

import { Container, Nav, Navbar } from "react-bootstrap";

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";

export default class NavBar extends Component {
  // Class implementation here...
}

CSS (demo):

.nav {
  min-height: 55px;
  width: 100%;
  background-color: white;
  border-bottom: 1px solid #979797;
}

.link {
  font-size: 14px;
  color: #3e433e;
  line-height: 17px;
  padding: 5px;
  text-transform: uppercase;
}

/* More CSS styles... */

Answer №1

Could you kindly review the link code provided below? We have made some adjustments to ensure a smooth transition effect. All declarations for .overlay.open have been relocated to .overlay and we've included a transition in the default state of .overlay, eliminating the need for it in .overlay.open.

To achieve a smooth transition, we've added transitions for height and opacity in the default state:

transition: opacity 0.4s ease-in-out, height 0.4s ease-in-out
.

1. Default State - .overlay:

height is set to '0px' and opacity is set to '0'.

2. Open State - .overlay.open:

height is set to '100%' and opacity is set to '1'.

Please check out this link for more details: https://codesandbox.io/s/summer-microservice-6d4c6

Answer №2

First Step:

To begin, transfer the overlay styles to its base CSS definition. Keep only the CSS properties in the .open class that should change when opening. For example, if we want to adjust the height, include height: 0 in the base .overlay CSS and height: 100% in the .overlay.open section.

Second Step:

Introduce a CSS transition (such as transition: height .5s ease) into the base CSS code and specify transition: none for the .overlay.open section. This will ensure that the transition effect is applied only when the element does not have the .open class. As a result, the overlay will open instantly but close with an animation.

If you would like to see the expected outcome, visit this link: https://codesandbox.io/s/charming-drake-dbtce?file=/src/styles.css

Answer №3

To avoid using an overlapping div to cover the full body, we can simply manage it with CSS properties.

Here is a code snippet that can help you solve your issue:

React code:

import React, { Component } from "react";

import { Container, Nav, Navbar } from "react-bootstrap";

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";

export default class NavBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
      data: []
    };
  }

  componentDidMount() {
    this.setState({
      data: [
        { name: "Test1" },
        { name: "Test2" },
        { name: "Test3" },
        { name: "Test4" }
      ]
    });
  }

  render() {
    return (
      <>
        <Navbar
          className={`nav ${this.state.open ? "open" : ""}`}
          expand="lg"
          sticky="top"
        >
          <Container>
            <Navbar.Toggle aria-controls="navbar-menu" />
            <Navbar.Collapse id="navbar-menu">
              <Nav className="ml-auto">
                {this.state.data.map((category) => (
                  <Nav.Link href="#" key={`category-${category.name}`}>
                    <span className="link">{category.name}</span>
                  </Nav.Link>
                ))}
              </Nav>
            </Navbar.Collapse>
          </Container>
        </Navbar>
        <img src="https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMjA3fDB8MXxzZWFyY2h8Nnx8bmF0dXJhbHx8MHx8fA&ixlib=rb-1.2.1&q=80&w=1080" />
      </>
    );
  }
}

CSS Code:

.nav {
  min-height: 55px;
  width: 100%;
  background-color: white;
  border-bottom: 1px solid #979797;
}

.link {
  font-size: 14px;
  color: #3e433e;
  line-height: 17px;
  padding: 5px;
  text-transform: uppercase;
}

.link:hover {
  color: #000000;
  text-decoration: none;
}

@media (max-width: 991px) {
  #navbar-menu {
    position: fixed;
    top: 57px;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 0 10px;
    height: 0 !important;
    transition: height 0.3s ease-out !important;
    -webkit-transition: height 0.3s ease-out !important;
    overflow: hidden;
  }
  #navbar-menu.show {
    height: calc(100vh - 57px) !important;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to assign a value to a variable in JavaScript

Today, I delved into the world of JavaScript and decided to test my skills by creating a page that changes images when clicking on a div. Everything worked perfectly until I wanted to add an input element to specify how many steps to jump each time the but ...

Conceal the overflow from absolutely positioned elements

I've gone through all the similar examples but still struggling to find the correct solution. My issue involves a basic Side Menu that toggles upon button click. Within the menu, there is a list of checkboxes positioned absolutely with the parent con ...

Using a React component to import a module for publishing on NPM

Creating my first React component for NPM publication has been quite the learning experience. I decided to use the react-webpack-component package from Yeoman to kickstart my project. However, upon installing and importing my component into a React app, I ...

What is the most effective approach to seamlessly conceal and reveal a button with the assistance

I have two buttons, one for play and one for pause. <td> <?php if($service['ue_status'] == "RUNNING"){ $hideMe = 'd-none'; } ?> <a href="#" class="btn btn-warning ...

An issue with the animation script in Ionic

I'm having trouble converting this to an Ionic application. Here's my code sample. Can anyone help me with putting this code correctly in Ionic? I'm trying to achieve something like this example <script src="https://cdnjs.cloudflare.com ...

Smooth animation is not being achieved with the Jquery dlmenu

I have implemented a multi-level navigation menu using a demo of the jquery dlmenu plugin v1.0.2. Although most of the functions are working smoothly, the CSS3 menu navigation lacks the fluidity of the jQuery left/right sliding effect. Is there a way to ...

The Boostrap Datepicker fails to display

I'm having trouble integrating a Bootstrap Datepicker into my form. I got it working outside of the form, but when I try to include the code in my form, it doesn't seem to work. All necessary files are present and the code is identical. <!D ...

Settings for the packaging of web components

Is there a way to configure a web component in vue.config.js and separate the iconfont.css section when building? I am using the vue-cli-service build --target wc-async --name chat-ui src/views/Chat/Launcher.vue --report command to package the web compon ...

Is organizing a table into separate sections helpful?

I'm currently working on a personal project using Material UI, but I have a more general query regarding table implementation. I have designed a layout in Figma that I like, but I am struggling to translate it into code. https://i.sstatic.net/NoWEB.p ...

Unable to access the redux store directly outside of the component

When trying to access my store from a classic function outside the component, I encountered an error while calling getState(): Property 'getState' does not exist on type '(initialState: any) => any' Below is the declaration and im ...

Custom Bootstrap 3 Panel Organization

I'm intrigued by the layout shown in the image attached. My attempts to recreate it using a combination of columns and rows have been unsuccessful. Could it be that I'm going about this the wrong way? ...

Issue with DataGrid in Material-UI preventing deletion of input value due to loss of focus

I have been experimenting with the Material-UI DataGrid component and I encountered an issue. I am trying to include a button inside one of the columns of the table that opens a Modal with a form inside. However, I noticed that when I try to type in the fo ...

ReactJS presents a limitation where style cannot be altered as the state changes

Currently, I am a beginner in ReactJS and I am still in the learning process. Recently, I wrote a simple code to experiment with style changes. However, upon changing the state in React, I expected the component to re-render, but that did not happen as a ...

How to perfectly align content on a webpage

Can someone help me understand why my webpage is off-centered as it scales up? I have set a minimum width of 1000px, but it still appears to be centered at 30%-70%. Any insights on this issue would be greatly appreciated. <!DOCTYPE html PUBLIC "-//W3 ...

Implementing a clickable search icon within a form input field using CSS: a guide

I have added a search icon to the form input field. Check it out here: https://i.sstatic.net/pnv6k.jpg #searchform { position: relative; } #searchform:before { content: "\f118"; font-family: "pharma"; right: 0px; position: absolute; ...

Adjust the background color of the active tab in Material-UI using React

Is there a way to customize the background color of the active tab in material-ui Tabs component? I already know how to change the underline with inkBarStyle={{background: 'red'}}, but I'm struggling to change the background color. Any help ...

What is the best way to retrieve the input value from a MUI TextField using cypress?

Currently, I am utilizing cypress to verify if a textfield correctly displays the entered text. cy.get('.creation-name').should('not.have.text'); const testName = 'Test name'; cy.get('.creation-name').type(`${testNam ...

What is causing the extra whitespace on the right side with container-fluid?

Could someone assist me with an issue I'm experiencing when using the container-fluid in Bootstrap? It seems to be leaving some space on the right side of my web page, and as a newcomer to Bootstrap, any help would be greatly appreciated. <link ...

The CSS styles do not seem to be taking effect on the Bootstrap

Here's a snippet of code extracted from my website's html and css files. My intention is to make the navbar slightly transparent with centered links, but for some reason, the css styles are not applying correctly to the navbar. HTML <body ...

Tips for maximizing page layout efficiency without compromising on element visibility

What is occurring https://i.stack.imgur.com/Agjw6.gif The use of .hide() and .fadeIn(200) is resulting in a jittery effect that I would like to avoid. Desired Outcome When the user hovers over the menu icon, the menu icon should vanish the text "Pr ...