2012-08-13 20 views
28

Estoy creando un sitio web de ejemplo que tiene tres divisiones horizontalmente. Quiero que el div más izquierdo sea del 25% de ancho, el del medio tenga un 50% de ancho y el derecho sea del 25% de ancho para que las divisiones llenen todo el espacio del 100% horizontalmente.¿Cómo colocar tres divs en html horizontalmente?

<html> 
    <title> 
    Website Title 
    </title> 

    <div id="the whole thing" style="height:100%; width:100%" > 

     <div id="leftThing" style="position: relative; width:25%; background-color:blue;"> 
      Left Side Menu 
     </div> 

     <div id="content" style="position: relative; width:50%; background-color:green;"> 
      Random Content 
     </div> 

     <div id="rightThing" style="position: relative; width:25%; background-color:yellow;"> 
      Right Side Menu 
     </div> 

    </div> 
</html> 

http://imgur.com/j4cJu

Cuando ejecuto este código, los divs aparecen unos sobre otros. ¡Quiero que aparezcan uno al lado del otro!

¿Cómo puedo hacer esto?

+0

Dale la izquierda div el estilo "float: left" y el "flotar div derecha :derecho". –

+0

Hazlos flotar a la izquierda, apilarán uno tras otro. Sin embargo, no estoy seguro de que el% de ancho se siga aplicando, debes probarlo. – Terry

+0

@ user1594853 Si una respuesta lo ayudó, márquela como aceptada. –

Respuesta

9

Puede utilizar floating elements así:

<div id="the whole thing" style="height:100%; width:100%; overflow: hidden;"> 
    <div id="leftThing" style="float: left; width:25%; background-color:blue;">Left Side Menu</div> 
    <div id="content" style="float: left; width:50%; background-color:green;">Random Content</div> 
    <div id="rightThing" style="float: left; width:25%; background-color:yellow;">Right Side Menu</div> 
</div> 

Nota del overflow: hidden; en el contenedor principal, esto es para que el elemento primario crezca y tenga las mismas dimensiones que los elementos secundarios (de lo contrario, tendrá una altura de 0).

+3

Si bien el flotador es correcto, no recomendaría un "HTML newb" "para comenzar a usar CSS en línea. Editar: se dio cuenta ahora que ya estaba usando CSS en línea, aún así sugeriría una mejor solución. – powerbuoy

+0

@powerbuoy acordado, CSS en línea NO es recomendable. Esto se haría desde un archivo CSS incluido donde los estilos están vinculados a través de id (#leftThing {float: left;}), selector o nombre de clase. –

2

se agrega una

float: left; 

al estilo de los 3 elementos y asegúrese de que el contenedor primario tiene

overflow: hidden; position: relative; 

esto hace que los flotadores ocupan un espacio real.

<html> 
    <head> 
     <title>Website Title </title> 
    </head> 
    <body> 
     <div id="the-whole-thing" style="position: relative; overflow: hidden;"> 
      <div id="leftThing" style="position: relative; width: 25%; background-color: blue; float: left;"> 
       Left Side Menu 
      </div> 
      <div id="content" style="position: relative; width: 50%; background-color: green; float: left;"> 
       Random Content 
      </div> 
      <div id="rightThing" style="position: relative; width: 25%; background-color: yellow; float: left;"> 
       Right Side Menu 
      </div> 
     </div> 
    </body> 
</html> 

también tenga en cuenta que la anchura: 100% y altura: 100% necesita ser retirado del recipiente, de lo contrario la tercera bloque envolverá a una segunda línea.

0

Deshágase de position:relative; y reemplácelo por float:left; y float:right;.

Ejemplo de jsFiddle: http://jsfiddle.net/d9fHP/1/

 <html> 
<title> 
Website Title </title> 
<div id="the whole thing" style="float:left; height:100%; width:100%"> 
    <div id="leftThing" style="float:left; width:25%; background-color:blue;"> 
     Left Side Menu 
    </div> 
    <div id="content" style="float:left; width:50%; background-color:green;"> 
     Random Content 
    </div> 
    <div id="rightThing" style="float:right; width:25%; background-color:yellow;"> 
     Right Side Menu 
    </div> 
</div> 
</html>​ 
24

Me abstenerse de utilizar flotadores para este tipo de cosas; Prefiero usar inline-block.

Algunas cuestiones a tener en cuenta:

  • de estilos en línea son malos para el mantenimiento
  • Usted no debe tener espacios en los nombres de selector
  • se ausentó etiquetas HTML importantes, como <head> y <body>
  • No incluyó un doctype

Aquí hay una mejor manera de dar formato al documento:

<!DOCTYPE html> 
<html> 
<head> 
<title>Website Title</title> 
<style type="text/css"> 
* {margin: 0; padding: 0;} 
#container {height: 100%; width:100%; font-size: 0;} 
#left, #middle, #right {display: inline-block; *display: inline; zoom: 1; vertical-align: top; font-size: 12px;} 
#left {width: 25%; background: blue;} 
#middle {width: 50%; background: green;} 
#right {width: 25%; background: yellow;} 
</style> 
</head> 
<body> 
<div id="container"> 
    <div id="left">Left Side Menu</div> 
    <div id="middle">Random Content</div> 
    <div id="right">Right Side Menu</div> 
</div> 
</body> 
</html> 

Aquí hay una jsFiddle una buena medida.

+3

Es bueno que sugiera cambiar de CSS en línea. También puedo señalar que "izquierda", "media" y "derecha" son realmente malas identificaciones (o nombres de clase) ya que están directamente relacionadas con su diseño en lugar de su significado. Además, no recomendaría 'inline-block' para esto sobre' float'.Un elemento 'inline-block' se ve afectado por' letter-spacing' y 'font-size' (etc.) lo que los hace más difíciles de alinear (una solución es establecer' font-size: 0' en '# container' y luego volviendo a la normalidad en '#container *'). – powerbuoy

+0

Sí, eso es totalmente cierto. –

+0

"Te perdiste algunas etiquetas HTML importantes, como y " Técnicamente no hay nada de malo en eso en estos días ...: https://html.spec.whatwg.org/multipage/syntax.html#optional-tags – roundar

8

Sé que esta es una pregunta muy antigua. Solo publicando esto aquí mientras resolvía este problema usando FlexBox.Aquí está la solución

#container { 
 
    height: 100%; 
 
    width: 100%; 
 
    display: flex; 
 
} 
 
#leftThing { 
 
    width: 25%; 
 
    background-color: blue; 
 
} 
 
#content { 
 
    width: 50%; 
 
    background-color: green; 
 
} 
 
#rightThing { 
 
    width: 25%; 
 
    background-color: yellow; 
 
}
<div id="container"> 
 

 
    <div id="leftThing"> 
 
    Left Side Menu 
 
    </div> 
 

 
    <div id="content"> 
 
    Random Content 
 
    </div> 
 

 
    <div id="rightThing"> 
 
    Right Side Menu 
 
    </div> 
 

 
</div>

sólo tenía que añadir display:flex al contenedor! No se requieren flotadores.

6

La manera más fácil
puedo ver la pregunta se responde, estoy dando esta respuesta para los que está teniendo esta cuestión en el futuro


No es una buena práctica codificar css en línea, y también ID para todas las div internas, siempre intente utilizar clase para darle estilo. Usar css en línea es una muy mala práctica si está tratando de ser un diseñador web profesional.

aquí en su pregunta me han dado una clase contenedora para el div padre y todos los dentro del div div son niños de CSS en los que puede llamar interiores de div utilizando nth-child selector.

quiero señalar algunas cosas aquí

1 - No utilizar CSS en línea (es muy mala práctica)

2 - Trate de usar las clases en lugar de la palabra porque si se le da un identificador que pueda Úselo solo una vez, pero si usa una clase, puede usarla muchas veces y también puede usar estilos de esa clase para escribir menos código.


enlace codepen mi respuesta

https://codepen.io/feizel/pen/JELGyB



             
  
  .wrapper{width:100%;} 
 
      .box{float:left; height:100px;} 
 
      .box:nth-child(1){ 
 
       width:25%; 
 
       background-color:red; 
 
     
 
      } 
 
      .box:nth-child(2){ 
 
       width:50%; 
 
       background-color:green; 
 
      } 
 
      .box:nth-child(3){ 
 
       width:25%; 
 
       background-color:yellow; 
 
      }

 
    <div class="wrapper"> 
 
     <div class="box"> 
 
     Left Side Menu 
 
     </div> 
 
     <div class="box"> 
 
     Random Content 
 
     </div> 
 
     <div class="box"> 
 
     Right Side Menu 
 
     </div> 
 
    </div>

Cuestiones relacionadas