Portada » Lenguaje PHP » Crear div flotante usando CSS y Bootstrap: 3 ejemplos

Crear div flotante usando CSS y Bootstrap: 3 ejemplos

Crear div flotante usando CSS y Bootstrap. En este artículo veremos cómo crear un DIV flotante y que nos siga si bajamos con el SCROLL, es decir un div que nos sigue con el scroll y mostraremos 3 ejemplos completos.

¿Para qué me sirva crear div flotante?

Si tienes páginas con bastante contenido y generándose scroll en la pantalla del navegador puede ser interesante mantener visible un DIV para mostrar un menú o buscador web.

Mostrar un anuncio publicitario o promociones. (¡aprovecha este Black Friday con ofertas imperdibles!) si es que vendemos algún producto.

Los usos son variados y dependerá de la necesidad del desarrollador o la empresa.

Crear div flotante usando CSS y Bootstrap
Crear div flotante usando CSS y Bootstrap

Ventajas de aplicar esta técnica de crear div flotante

  • Ventas. – Si tu sitio es un Ecommerce, obviamente estas poniendo el producto delante de un potencial cliente y se reflejara en ventas.
  • Publicidad. – Aunque suele ser molestoso la publicidad, también podemos colocar un anuncio en un DIV fijo lo que lograra será más conversiones.
  • Opciones. – Si es un sistema web, estarías mostrando al usuario final las opciones de configuración siempre a la mano, por ejemplo, el botón «Guardar registro» o «Editar registros«.
  • Navegación. – Ayuda a la navegación porque las opciones siempre serán visibles, como ser por ejemplo el correo «GMAIL» a pesar que bajamos el scroll las opciones del lado izquierdo siempre están visibles.

La solución es: Crear div flotante

A continuación, veremos 3 formas para crear DIV flotantes en nuestro sitio web o sistema web.

Usando estilos CSS

Para darle solución a este problema puedes utilizar el atributo position de CSS en el contenedor que queremos tener siempre visible, ejemplo:

position: fixed;

Para tenerlo más ordenado podemos crear una clase CSS llamado «div-fixed» que sería una clase personalizada por el programador.

El código CSS que necesitamos para fijar una determinada etiqueta es el siguiente:

.div-fixed {
position: fixed;
min-height: 120px;
text-align: center;
word-wrap: break-word;
width: 252px;
}

Si observa domos la clase anterior hemos aplicado propiedades y valores que significa lo siguiente:

  • Se declaró una posición fija.
  • Establecemos una altura mínima de 120px.
  • Un ancho de 252px.
  • El texto centrado.
  • Evitamos que el texto se salga del contenedor.

Luego, dentro de las etiquetas <body> tenemos nuestro código HTML:

<div class="div-fixed bg-warning">
<p>Div izquierda que esta fijo...</p>
<p><a class="btn btn-primary" href="index-con-bootstrap.html">Ver ejemplo con Bootstrap</a></p>
</div>

Script completo usando CSS

<!doctype html>
<html lang="en" class="h-100">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.88.1">
<title>Position Fixed CSS Demo</title>

<link rel="stylesheet" href="css/font-awesome.min.css">
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/styles.css">

</head>
<body>
<header>
<!-- Fixed navbar -->
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<div class="container">
<a class="navbar-brand" href="https://baulphp.com/">BaulPHP</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<li class="nav-item">
<a class="nav-link" href="#">Ver Artículo</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://baulphp.com/download-category/php-files/">Más descargas</a>
</li>

</ul>

</div>
</div>
</nav>
</header>

<!-- Begin page content -->
<main class="flex-shrink-0">
<div class="container">
<h1>Position Fixed CSS</h1>
<h2 class="lead">Crear div flotante usando 3 ejemplos</h2>


<nav style="--bs-breadcrumb-divider: url(&#34;data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8'%3E%3Cpath d='M2.5 0L1 1.5 3.5 4 1 6.5 2.5 8l4-4-4-4z' fill='currentColor'/%3E%3C/svg%3E&#34;);" aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Blog</a></li>
<li class="breadcrumb-item active" aria-current="page">Crear div flotante usando 3 ejemplos</li>
</ol>
</nav> 
</div>

<div class="container">
<div class="row">
<div id="column_left" class="col-xs-12 col-lg-3">
<div class="div-fixed bg-warning">
<p>Div izquierda que esta fijo...</p>
<p><a class="btn btn-primary" href="index-con-bootstrap.html">Ver ejemplo con Bootstrap</a></p>
</div>
</div>
<div id="content" class="col-xs-12 col-lg-9">
<h2>Mi artículo...</h2>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

</div>

</div>


</div>

</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Usando Framework BootStrap

Si usas Bootstrap 5 en tu sitio o sistema web, podemos conseguir un resultado mucho más sencillo y preciso. Por lo tanto, solo tienes que añadir la clase «position-fixed» al DIV que quieres fijar, por ejemplo:

<div class="position-fixed">
Columna izquierda que se mueve con el scroll...
</div>

La clase «position-fixed» viene predefinido con el framework Bootstrap y podemos usarlo en nuestros proyectos, dando resultados muy eficaces.

Script completo

<!doctype html>
<html lang="en" class="h-100">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.88.1">
<title>Crear div flotante usando 3 ejemplos</title>

<link rel="stylesheet" href="css/font-awesome.min.css">
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/styles.css">

</head>
<body>
<header>
<!-- Fixed navbar -->
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<div class="container">
<a class="navbar-brand" href="https://baulphp.com/">BaulPHP</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<li class="nav-item">
<a class="nav-link" href="#">Ver Artículo</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://baulphp.com/download-category/php-files/">Más descargas</a>
</li>

</ul>

</div>
</div>
</nav>
</header>

<!-- Begin page content -->
<main class="flex-shrink-0">
<div class="container">
<h1>Position Fixed Usando BootStrap</h1>
<h2 class="lead">Crear div flotante usando 3 ejemplos</h2>


<nav style="--bs-breadcrumb-divider: url(&#34;data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8'%3E%3Cpath d='M2.5 0L1 1.5 3.5 4 1 6.5 2.5 8l4-4-4-4z' fill='currentColor'/%3E%3C/svg%3E&#34;);" aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Blog</a></li>
<li class="breadcrumb-item active" aria-current="page">Crear div flotante usando 3 ejemplos</li>
</ol>
</nav>


<div class="row">
<div id="column_left" class="col-xs-12 col-lg-3">
<div class="position-fixed bg-warning">
<p>Columna izquierda que se mueve con el scroll...</p>
<p><a class="btn btn-secondary" href="index.html">Ver ejemplo sin Bootstrap</a></p>
</div>
</div>
<div id="content" class="col-xs-12 col-lg-9">
<h2>Mi Artículo</h2>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

</div>
</div>





</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

DIV QUE TE SIGUE CON EL SCROLL

Aquí les mostrare otro script usando CSS y HTML para que el div te siga si mueves el SCROLLBAR del navegador web.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Div que te sigue con el scroll</title>
<style>
#content {
width: 100%;
margin: 0px auto;
}
#column-left {
background-color: #EBE9EA;
border: 1px solid #D2D2D2;
border-radius: 8px 8px 8px 8px;
float: left;
/* para mantener visible un elemento en todo momento aunque se haga scroll en la página */
position: fixed;
min-height: 225px;
margin-bottom: 10px;
overflow: hidden;
text-align: center;
width: 26%;
padding: 6px;
}
#central {
background-color: #EBE9EA;
border: 1px solid #D2D2D2;
border-radius: 8px 8px 8px 8px;
float: right;
height: 5000px;
margin-bottom: 10px;
width: 68%;
padding: 4px;
}
</style>
</head>

<body>
<div id="content">
<div id="column-left">Columna izquierda que se mueve con el scroll...</div>
<div id="central">Bloque central</div>
</div>
</body>
</html>

Conclusión

La implementación de un DIV fijo es muy sencillo y en este artículo hemos realizado 3 ejemplos completos. Además, hemos visto que se pueden realizar usando CSS o usando el Framework Boostrap5.

Además, a estos DIV flotantes se pueden agregar conexión a base de datos y usando el ciclo foreach para mostrar información de BD.

Sin duda esta implementación es requerida por grades compañías porque dan muy buenos resultados en varios ámbitos. Sin embargo, tienes sus ventajas y debemos de aprovecharlo al máximo.

Les dejare el link de descarga del script con los tres ejemplos.

Descargar

¿De cuánta utilidad te ha parecido este contenido?

¡Haz clic en una estrella para puntuarlo!

Promedio de puntuación 5 / 5. Recuento de votos: 1

Hasta ahora, ¡no hay votos!. Sé el primero en puntuar este contenido.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Scroll al inicio
Esta web utiliza cookies propias para su correcto funcionamiento. Contiene enlaces a sitios web de terceros con políticas de privacidad ajenas que podrás aceptar o no cuando accedas a ellos. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos.
Privacidad