CSS para alinear la etiqueta y la entrada


Fragmento de código HTML:

<fieldset id="o-bs-sum-buginfo">
  <label for="o-bs-sum-bug-ErrorPrefix">Error Prefix</label>
  <input type="text" id="o-bs-sum-bug-ErrorPrefix" name="ErrorPrefix" value="" />

  <label for="o-bs-sum-bug-ErrorNumber">Error Number</label>
  <input type="text" id="o-bs-sum-bug-ErrorNumber" name="ErrorNumber" value="" />
  ....
</fieldset>

Usando solo CSS (o jquery), independientemente del tamaño del navegador, quiero emparejar los elementos label y input uno al lado del otro. También tengo la libertad de cambiar ajustar el HTML. si es necesario.

Author: hashg, 2011-01-09

6 answers

Esta es una de esas cosas que puede ser sorprendentemente difícil de hacer bien.

Muchas personas sugerirán usar float:left; para esto. Personalmente, realmente no me gustan las carrozas; parecen causar más problemas de los que resuelven.

Mi preferencia es usar el bloque en línea. Este es un método de visualización que combina propiedades en línea (para que pueda alinear fácilmente elementos uno junto al otro, etc.) con propiedades de bloque (como poder especificar dimensiones).

Así que la respuesta es simplemente haga ambos display:inline-block; y dé a las indicaciones un ancho fijo, lo que hará que los campos de entrada junto a ellos se alineen.

También necesitará algún tipo de salto o salto de línea después del campo de entrada, de lo contrario, el siguiente mensaje aparecerá en la misma línea, que no es el efecto deseado. La mejor manera de lograr esto es poner cada mensaje y su campo en un contenedor <div>.

Así que su HTML se verá así:

<fieldset id="o-bs-sum-buginfo" class="myfields">
  <div>
    <label for="o-bs-sum-bug-ErrorPrefix">Error Prefix</label>
    <input type="text" id="o-bs-sum-bug-ErrorPrefix" name="ErrorPrefix" value="" />
  </div>

  <div>
    <label for="o-bs-sum-bug-ErrorNumber">Error Number</label>
    <input type="text" id="o-bs-sum-bug-ErrorNumber" name="ErrorNumber" value="" />
  </div>
  ....
</fieldset>

Y su CSS se verá así:

.myfields label, .myfields input {
  display:inline-block;
}

.myfields label {
  width:200px; /* or whatever size you want them */
}

Espero que ayudar.

Editar: puedes usar este plugin para establecer el ancho de cada etiqueta:

jQuery.fn.autoWidth = function(options) 
{ 
  var settings = { 
        limitWidth   : false 
  } 

  if(options) { 
        jQuery.extend(settings, options); 
    }; 

    var maxWidth = 0; 

  this.each(function(){ 
        if ($(this).width() > maxWidth){ 
          if(settings.limitWidth && maxWidth >= settings.limitWidth) { 
            maxWidth = settings.limitWidth; 
          } else { 
            maxWidth = $(this).width(); 
          } 
        } 
  });   

  this.width(maxWidth); 
}

De esta página en un comentario

Y lo usas de esta manera:

$("div.myfields div label").autoWidth();

Y eso es todo... todas sus etiquetas van a tomar el ancho de la etiqueta más larga

 84
Author: Spudley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-06 12:02:16

#o-bs-sum-buginfo label, #o-bs-sum-buginfo input{display:inline-block;width:50%;}

 10
Author: Shahid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-09 19:58:30

Coloque la etiqueta every con su entrada correspondiente en una etiqueta p. A continuación, agregue el siguiente css:

label{
  float:left;
  width:100px; //whatever width that suits your needs
}

p{
    margin:10px 0; //manipulate the vertical spaces for each input..  
}



<fieldset id="o-bs-sum-buginfo">
  <p>
    <label for="o-bs-sum-bug-ErrorPrefix">Error Prefix</label>
    <input type="text" id="o-bs-sum-bug-ErrorPrefix" name="ErrorPrefix" value="" />
  </p>
</fieldset>
 1
Author: amosrivera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-09 19:56:33

Creo que usar javascript para un simple truco css es excesivo. Aquí está el que acabo de hacer.: http://jsfiddle.net/t6R93 /

div{
  display: table-row;
}
label,input{
  display:table-cell;
}

PD: Puede tener defectos con otros navegadores. Solo probé con Chrome.

 1
Author: egiray,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-15 18:32:55

No es necesario usar JavaScript, jQuery o divs adicionales. Solo tienes que:

  • Flote tanto input como label a la izquierda (tenga en cuenta que input tiene que ser bloque para flotar).
  • Añadir clear: both a label.
  • Establezca el ancho fijo (por ejemplo, 100px) en label.

input {
  display: block;
  float: left;
}
label {
  float: left;
  clear: both;
  width: 100px;
}
<fieldset id="o-bs-sum-buginfo">
  <label for="o-bs-sum-bug-ErrorPrefix">Error Prefix</label>
  <input type="text" id="o-bs-sum-bug-ErrorPrefix" name="ErrorPrefix" value="" />

  <label for="o-bs-sum-bug-ErrorNumber">Error Number</label>
  <input type="text" id="o-bs-sum-bug-ErrorNumber" name="ErrorNumber" value="" />
</fieldset>
 1
Author: Michał Perłakowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-07 21:14:29

Tenía curiosidad por ver si esto se podía hacer con el marcado semántico" natural", es decir, sin elementos de envoltura no semántica y con el label que contiene su correspondiente input en lugar de tener que referirse a él con el atributo for ligeramente torpe:

<fieldset>
  <label>Error Prefix<input/></label>
  <label>Error Number<input/></label>
</fieldset>

Una etiqueta de ancho fijo no alineará las entradas aquí porque el texto no es un elemento separado, y la solución elegantemente mínima de Shahid tampoco funciona, pero si está dispuesto a hacer que todas las entradas tengan el mismo ancho (que Mi humilde opinión se ve bien de todos modos) usted puede float ellos right:

label { display:block; margin:8px; width:360px; clear:right; overflow:auto; }
input, button, textarea, select { box-sizing:border-box; -moz-box-sizing:border-box; width:200px; float:right; }

El -moz-box-sizing debería ser redundante cuando se libera FF29, e incluso el box-sizing no es necesario a menos que esté mezclando tipos de control de forma. Los clear y overflow son específicamente necesarios para textarea.

Ejemplo completo de entrada mixta:

<!DOCTYPE html>
<html>
  <head>
    <title>Aligned labels</title>
    <style>
      label { display:block; margin:8px; width:360px; clear:right; overflow:auto; }
      input, button, textarea, select { box-sizing:border-box; -moz-box-sizing:border-box; width:200px; float:right; }
    </style>
  </head>
  <body>
    <label>Name<input type="text" value="Sir Galahad of Camelot"/></label>
    <label>Quest<textarea>I seek the Holy Grail</textarea></label>
    <label>Favourite Colour<select><option>Blue</option><option>Yellow</option></select></label>
    <label>If you're sure...<button>Give Answers</button></label>
  </body>
</html>
 0
Author: mrec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-03 17:44:41