1. Web Design
  2. HTML/CSS
  3. CSS

Haciendo un Menú de Navegación Lateral Deslizante para Diseños Responsivos

Scroll to top

Spanish (Español) translation by David Castrillón (you can also view the original English article)

En este tutorial, crearás un menú de navegación lateral expandible con JavaScript y CSS. El producto final aparecerá como se muestra a continuación:

Sliding Side Navigation MenuSliding Side Navigation MenuSliding Side Navigation Menu

El Marcado

Para empezar, vamos a añadir algo de marcado para nuestro menú lateral:

1
  <div id="sideNavigation" class="sidenav">
2
    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
3
    <a href="#">About</a>
4
    <a href="#">Features</a>
5
    <a href="#">Contact Us</a>
6
  </div>
7
8
  <nav class="topnav">
9
    <a href="#" onclick="openNav()">
10
      <svg width="30" height="30" id="icoOpen">
11
          <path d="M0,5 30,5" stroke="#000" stroke-width="5"/>
12
          <path d="M0,14 30,14" stroke="#000" stroke-width="5"/>
13
          <path d="M0,23 30,23" stroke="#000" stroke-width="5"/>
14
      </svg>
15
    </a>
16
  </nav>
17
  
18
  <div id="main">
19
  <!-- Add all your websites page content here  -->
20
  </div>

Aquí puedes ver que creamos un div para el menú lateral con la clase sidenav. A continuación agregamos la barra superior de navegación a través de una etiqueta <nav> y estamos utilizando un SVG para nuestro icono del menú lateral.

El atributo onclick del icono y el botón de cerrar activará algunos JavaScript, que añadiremos a continuación.

Recuerda poner todo el contenido de tu sitio web dentro del contenedor div id="main"  para que se deslice hacia la derecha.

JavaScript

A continuación, vamos a agregar el JavaScript para hacer las funciones openNav y closeNav.

1
<script>
2
function openNav() {
3
    document.getElementById("sideNavigation").style.width = "250px";
4
    document.getElementById("main").style.marginLeft = "250px";
5
}
6
7
function closeNav() {
8
    document.getElementById("sideNavigation").style.width = "0";
9
    document.getElementById("main").style.marginLeft = "0";
10
}
11
</script>

CSS

Por último, tenemos que darle estilo a nuestra página con algunos CSS para el menú lateral y nuestros enlaces:

1
/* The side navigation menu */
2
.sidenav {
3
    height: 100%; /* 100% Full-height */
4
    width: 0; /* 0 width - change this with JavaScript */
5
    position: fixed; /* Stay in place */
6
    z-index: 1; /* Stay on top */
7
    top: 0;
8
    left: 0;
9
    background-color: #111; /* Black*/
10
    overflow-x: hidden; /* Disable horizontal scroll */
11
    padding-top: 60px; /* Place content 60px from the top */
12
    transition: 0.5s; /* 0.5 second transition effect to slide in the sidenav */
13
}
14
15
/* The navigation menu links */
16
.sidenav a {
17
    padding: 8px 8px 8px 32px;
18
    text-decoration: none;
19
    font-size: 25px;
20
    color: #818181;
21
    display: block;
22
    transition: 0.3s
23
}
24
25
/* When you mouse over the navigation links, change their color */
26
.sidenav a:hover, .offcanvas a:focus{
27
    color: #f1f1f1;
28
}
29
30
/* Position and style the close button (top right corner) */
31
.sidenav .closebtn {
32
    position: absolute;
33
    top: 0;
34
    right: 25px;
35
    font-size: 36px;
36
    margin-left: 50px;
37
}
38
39
/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
40
#main {
41
    transition: margin-left .5s;
42
    padding: 20px;
43
    overflow:hidden;
44
    width:100%;
45
}
46
body {
47
  overflow-x: hidden;
48
}
49
50
/* Add a black background color to the top navigation */
51
.topnav {
52
    background-color: #333;
53
    overflow: hidden;
54
}
55
56
/* Style the links inside the navigation bar */
57
.topnav a {
58
    float: left;
59
    display: block;
60
    color: #f2f2f2;
61
    text-align: center;
62
    padding: 14px 16px;
63
    text-decoration: none;
64
    font-size: 17px;
65
}
66
67
/* Change the color of links on hover */
68
.topnav a:hover {
69
    background-color: #ddd;
70
    color: black;
71
}
72
73
/* Add a color to the active/current link */
74
.topnav a.active {
75
    background-color: #4CAF50;
76
    color: white;
77
}
78
79
/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
80
@media screen and (max-height: 450px) {
81
    .sidenav {padding-top: 15px;}
82
    .sidenav a {font-size: 18px;}
83
}
84
85
a svg{
86
  transition:all .5s ease;
87
88
  &:hover{
89
    #transform:rotate(180deg);
90
  }
91
}
92
93
#ico{
94
  display: none;
95
}
96
97
.menu{
98
  background: #000;
99
  display: none;
100
  padding: 5px;
101
  width: 320px;
102
  @include border-radius(5px);
103
104
  #transition: all 0.5s ease;
105
106
  a{
107
    display: block;
108
    color: #fff;
109
    text-align: center;
110
    padding: 10px 2px;
111
    margin: 3px 0;
112
    text-decoration: none;
113
    background: #444;
114
115
    &:nth-child(1){
116
      margin-top: 0;
117
      @include border-radius(3px 3px 0 0 );
118
    }
119
    &:nth-child(5){
120
      margin-bottom: 0;
121
      @include border-radius(0 0 3px 3px);
122
    }
123
124
    &:hover{
125
      background: #555;
126
    }
127
  }
128
}

Nota: El body {overflow-x: hidden;} es necesario para asegurar que el desplazamiento horizontal no aparece cuando se usa con el CSS existente.

Ahora puedes echar un vistazo a tu menú y probarlo en tu navegador.

Utilizando jQuery

Si quieres crear el menú del lado de JavaScript utilizando jQuery, puedes hacerlo reemplazando el JavaScript que he proporcionado anteriormente con la siguiente sección:

1
$('.topnav a').click(function(){
2
  $('#sideNavigation').style.width = "250px";
3
  $("#main").style.marginLeft = "250px";
4
});
5
6
$('.closebtn').click(function(){
7
  $('#sideNavigation').style.width = "0";
8
  $("#main").style.marginLeft = "0";
9
});

Eliminando el Desplazamiento

Para que el menú aparezca sin ninguna animación de deslizamiento, simplemente realiza cambios en la propiedad transition del CSS, como se muestra de una forma abreviada a continuación:

1
.sidenav {
2
    transition: 0s; 
3
}
4
5
#main {
6
    transition: margin-left 0s;
7
}

Esto hará que el cambio aparezca al instante como si no hubiera ningún retraso en la propiedad transition. El valor predeterminado que usamos es 0,5.

Conclusión

Crear un menú lateral sólo toma unas pocas líneas de código y no es necesario utilizar muchos recursos. También, si jQuery ya está en la página para otras tareas, el trabajo puede ser hecho con menos líneas de código y puede ser modificado más allá para requisitos particulares.

Hacer el código responsivo para que trabaje con resoluciones de pantalla de diferentes dispositivos, es simplemente un caso de modificar el CSS añadiendo media queries para los casos concretos.

Para llevar esto más lejos, podrías querer estilizar tu menú con un framework CSS como Bootstrap o Bulma.