¿Cómo hacer un 'float: left' sin envolver?


Tengo un contenedor box1 que tiene un cierto ancho (que puede cambiar dependiendo de su contenido). Ese cuadro contiene box2 que tiene un ancho fijo (podría ser un icono). Junto a box2, tengo box3 con algo de texto. Quiero que el texto use todo el espacio disponible a la derecha de box2. Con el HTML pegado a continuación, obtienes:

Texto corto

Hasta ahora todo bien. Si el texto se hace más largo, no se envuelve box2 (que es lo que quiero), sin embargo, no hace que box1 crezca, que es mi problema. Me dirás " oye, si hiciste box3 un position: absolute, ¿cómo podrías esperar que haga crecer box1?". Bueno, yo no, pero entonces, ¿cómo puedo conseguir box3 para mostrar junto a box2, utilizar todo el espacio horizontal disponible, y hacer box1 crecer si es necesario? (¿Tengo que decir que me gustaría este trabajo en IE6 en adelante, y para evitar el uso de una tabla?)

Texto largo

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style type="text/css">
            #box1 { position: relative }
            #box3 { position: absolute; left: 2.5em; right: .5em; top: .5em }

            /* Styling */
            #box1 { background: #ddd; padding: 1em 0.5em; width: 20em }
            #box2 { background: #999; padding: .5em; }
            #box3 { background: #bbb; padding: .5em; }
            body  { font-family: sans-serif }
        </style>
        <script type="text/javascript">
        </script>
    </head>
    <body>
        <div id="box1">
            <span id="box2">2</span>
            <span id="box3">3</span>
        </div>
    </body>
</html>
Author: avernet, 2011-04-19

3 answers

Necesita que el cuadro 3 sea un elemento de nivel de bloque, así que use display:block y luego mezcle un overflow:hidden junto con float-ing box 2:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style type="text/css">
            #box1 {  }
            #box2 { float:left; }
            #box3 { display:block;overflow:hidden; }

            /* Styling */
            #box1 { background: #ddd; padding: 1em 0.5em; width: 20em }
            #box2 { background: #999; padding: .5em; }
            #box3 { background: #bbb; padding: .5em; }
            body  { font-family: sans-serif }

        </style>
        <script type="text/javascript">
        </script>
        <title>How to do a `float: left` with no wrapping?</title>
    </head>
    <body>
        <div id="box1">
            <span id="box2">2</span>
            <span id="box3">3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br /></span>
        </div>
    </body>
</html>

Asombroso todas las cosas overflow:hidden puede hacer: D

 38
Author: Richard JP Le Guen,
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-04-19 01:13:11

Hay un par de maneras de lograr esto. Dos comunes es tener un elemento vacío justo después con un clear: both así (css en línea solo para demo):

<span class="box1">...</span>
<br style="clear:both"/>

Otra forma es usar overflow: hidden así:

<span class="box1" style="overflow: hidden">...</span>

Sin embargo, hay problemas con ambas soluciones. Con el primero se agrega un marcado innecesario y feo. Y con el segundo si quieres que algo se coloque fuera de tu caja (como un position: absolute) no será visible.

Un más común, moderno la solución es usar el pseudo-elemento ::after y aclarar que así:

.box1::after {
    content: '';
    display: table;
    clear: both;
}
 2
Author: hesselbom,
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-12-03 09:47:43

Yo recomendaría lo siguiente:

#box1
{
    position: relative; /* or some other positioned value */
}

#box2
{
    width: 10px;
    height: 10px;
    position: absolute;
    top: 0;
    left: 0;
}

#box3
{
    margin-left: 10px;
}

Si #box2 es de un tamaño fijo, simplemente puede usar un margen para #box3 para evitar su superposición de #box2, y como no está posicionado, #box1 crecerá como #box3 crece.

 -3
Author: Jacob,
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-04-19 00:59:50