Foros del Web » Creando para Internet » CSS »

[APORTE] vertical-align para elementos de bloque

Estas en el tema de [APORTE] vertical-align para elementos de bloque en el foro de CSS en Foros del Web. Hola gente acá les traigo un pequeño aporte para todos los usuarios que tenemos esta duda... Ya que mucha gente no encuentra como hacer esto ...
  #1 (permalink)  
Antiguo 24/05/2011, 16:29
Avatar de BloodShadow  
Fecha de Ingreso: marzo-2010
Ubicación: El Salvador
Mensajes: 393
Antigüedad: 14 años
Puntos: 52
[APORTE] vertical-align para elementos de bloque

Hola gente acá les traigo un pequeño aporte para todos los usuarios que tenemos esta duda... Ya que mucha gente no encuentra como hacer esto y la solución que hacen es hacerlo con tablas o con padding pero nunca funciona bien con textos largo o algún otro inconveniente

El script lo hizo un compañero de donde trabajo y que es parte de la comunidad de foros del web el_quick así que por favor si usan el script no borren los créditos

Es un ejemplo sencillo con una simple lista pero si se fijan el elemento "a" esta con display: block para que vean que si funciona con elementos de bloque :D

antes que nada necesitan agregar al head el jquery y el script jquery.akomodate-links.js

Código HTML:
Ver original
  1. <script type="text/javascript" src="jquery.js"></script>
  2. <script type="text/javascript" src="jquery.akomodate-links.js"></script>

jquery.akomodate-links.js
Código Javascript:
Ver original
  1. /*
  2.  *      jquery.akomodate-links.js
  3.  *      
  4.  *      Copyright 2011 Ismael Rodríguez <[email protected]>
  5.  *      
  6.  *      This program is free software; you can redistribute it and/or modify
  7.  *      it under the terms of the GNU General Public License as published by
  8.  *      the Free Software Foundation; either version 2 of the License, or
  9.  *      (at your option) any later version.
  10.  *      
  11.  *      This program is distributed in the hope that it will be useful,
  12.  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  *      GNU General Public License for more details.
  15.  *      
  16.  *      You should have received a copy of the GNU General Public License
  17.  *      along with this program; if not, write to the Free Software
  18.  *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19.  *      MA 02110-1301, USA.
  20.  */
  21.  
  22. (function($){
  23.   $.fn.akomodateLinks = function(options){
  24.     var defaults  = {
  25.       "minLineHeight": 14,
  26.       "verticalCenter": true
  27.     };
  28.     var $settings = $.extend({}, defaults, options);  
  29.     var $broke = false;
  30.     this.css("line-height", function(){
  31.       $lh = parseInt($(this).css("line-height").replace(/[^0-9]/g, ''));
  32.       $ln = $(this).height() / $lh;
  33.       $(this).attr("ln", $ln);
  34.       $lh = ($lh / $ln);
  35.       if($lh < $settings.minLineHeight){
  36.         $lh = $settings.minLineHeight ;
  37.         $broke = true;
  38.       }
  39.       return $lh + "px";
  40.     });
  41.     if($broke){
  42.       $lh = Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get())
  43.       this.height($lh);
  44.       this.css("line-height", function(){
  45.         return ($lh / parseInt($(this).attr("ln"))) + "px";
  46.       });
  47.     }
  48.    
  49.     if($settings.verticalCenter){
  50.       this.css({
  51.         "padding-top" : function(){
  52.           return ((($(this).height() - ($settings.minLineHeight * parseInt($(this).attr("ln")))) / 2) + parseInt($(this).css("padding-top").replace(/[^0-9]/g, ''))) + "px";
  53.         },
  54.         "padding-bottom" : function(){
  55.           return ((($(this).height() - ($settings.minLineHeight * parseInt($(this).attr("ln")))) / 2) + parseInt($(this).css("padding-bottom").replace(/[^0-9]/g, ''))) + "px";
  56.         },
  57.         "line-height" : $settings.minLineHeight + "px",
  58.         "height" : ""
  59.       });
  60.     }
  61.   };
  62. })(jQuery);

luego de esto pasamos a crear un menú de ejemplo sencillo

Código HTML:
Ver original
  1. <ul id="menu">
  2.             <li>
  3.                 <a href="">Opcion 1</a>
  4.             </li>
  5.             <li>
  6.                 <a href="">Opcion 2</a>
  7.             </li>
  8.             <li>
  9.                 <a href="">Opcion 3 con mas texto</a>
  10.             </li>
  11.             <li>
  12.                 <a href="">Opcion 4</a>
  13.             </li>
  14.             <li>
  15.                 <a href="">Opcion 5 con mucho mas texto</a>
  16.             </li>
  17.             <li>
  18.                 <a href="">
  19.                     Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed tellus lectus, eget aliquam velit. Cras mattis, sem vel semper congue.
  20.                 </a>
  21.             </li>
  22.         </ul>

aca los estilos

Código CSS:
Ver original
  1. #menu                               { margin: 0px; padding: 0px; }
  2.     #menu li                        { float: left; width: 150px; margin: 0px 10px; background: pink; text-align: center; }
  3.     #menu li a                  { display: block; line-height: 30px; font-size: 14px; padding: 10px; }
  4.     #menu li a:hover        { text-decoration: underline; }

luego en el head crean la instancia del elemento a crear el vertical-align

Código Javascript:
Ver original
  1. <script type="text/javascript">
  2.             $(document).ready(function(){
  3.                 $('#menu li a').akomodateLinks({
  4.                     minLineHeight: '16',
  5.                     verticalCenter: true
  6.                 });
  7.             });
  8.         </script>

NOTA IMPORTANTE si se fijan en los estilos esta la clave, en la linea

Código CSS:
Ver original
  1. #menu li a                  { display: block; line-height: 30px; font-size: 14px; padding: 10px; }

el line-height es la clave de todo en este caso como en la instancia le aplicamos el script a #menu li a... a este elemento tenemos que aplicarle un line-height para que el script haga su trabajo :)

aca les dejo el código completo para que lo vean:

index.html
Código HTML:
Ver original
  1. <!DOCTYPE html
  2.     PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  3.     "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?= $lang ?>">
  5.     <head>
  6.         <link rel="stylesheet" type="text/css" href="styles.css" />
  7.         <script type="text/javascript" src="jquery.js"></script>
  8.         <script type="text/javascript" src="jquery.akomodate-links.js"></script>
  9.  
  10.         <script type="text/javascript">
  11.             $(document).ready(function(){
  12.                 $('#menu li a').akomodateLinks({
  13.                     minLineHeight: '16',
  14.                     verticalCenter: true
  15.                 });
  16.             });
  17.         </script>      
  18.     </head>
  19.     <body>
  20.         <ul id="menu">
  21.             <li>
  22.                 <a href="">Opcion 1</a>
  23.             </li>
  24.             <li>
  25.                 <a href="">Opcion 2</a>
  26.             </li>
  27.             <li>
  28.                 <a href="">Opcion 3 con mas texto</a>
  29.             </li>
  30.             <li>
  31.                 <a href="">Opcion 4</a>
  32.             </li>
  33.             <li>
  34.                 <a href="">Opcion 5 con mucho mas texto</a>
  35.             </li>
  36.             <li>
  37.                 <a href="">
  38.                     Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed tellus lectus, eget aliquam velit. Cras mattis, sem vel semper congue.
  39.                 </a>
  40.             </li>
  41.         </ul>
  42.     </body>
  43. </html>

styles.css
Código CSS:
Ver original
  1. a{ text-decoration: none; outline: 0; color: #42210b;; }
  2.  
  3. ul { list-style: none; }
  4.  
  5. /* En el código HTML es necesario añadir cellspacing="0" */
  6. table {
  7.   border-collapse: collapse;
  8.   border-spacing: 0;
  9. }
  10.  
  11. h1        { padding: 0; margin: 0; }
  12. h2        { padding: 0; margin: 0; }
  13. h3        { padding: 0; margin: 0; }
  14. h5              { padding: 0; margin: 0; }
  15. h6              { padding: 0; margin: 0; }
  16.  
  17. body{ font-family: Arial, Verdana, Helvetica, sans-serif; font-size: 12px; padding: 0; margin: 0; color: #42210b; }
  18.  
  19. /**************************************************************/
  20. /* STYLES INDEX */
  21. /**************************************************************/
  22.  
  23.     #menu                               { margin: 0px; padding: 0px; }
  24.     #menu li                        { float: left; width: 150px; margin: 0px 10px; background: pink; text-align: center; }
  25.     #menu li a                  { display: block; line-height: 30px; font-size: 14px; padding: 10px; }
  26.     #menu li a:hover        { text-decoration: underline; }

Espero les sirva y cualquier duda o error avisen por favor :D
  #2 (permalink)  
Antiguo 24/05/2011, 16:35
Avatar de BloodShadow  
Fecha de Ingreso: marzo-2010
Ubicación: El Salvador
Mensajes: 393
Antigüedad: 14 años
Puntos: 52
Respuesta: [APORTE] vertical-align para elementos de bloque

Este seria el resultado


Etiquetas: elementos, bloques
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 2 personas




La zona horaria es GMT -6. Ahora son las 17:07.