diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/pt-br/learn/css/css_layout | |
parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip |
initial commit
Diffstat (limited to 'files/pt-br/learn/css/css_layout')
7 files changed, 2525 insertions, 0 deletions
diff --git a/files/pt-br/learn/css/css_layout/flexbox/index.html b/files/pt-br/learn/css/css_layout/flexbox/index.html new file mode 100644 index 0000000000..f6e68c94d7 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/flexbox/index.html @@ -0,0 +1,342 @@ +--- +title: Flexbox +slug: Learn/CSS/CSS_layout/Flexbox +tags: + - Aprender + - Artigo + - CSS + - Caixas Flexíveis + - Flex + - Guía + - Iniciante + - Layout + - flexbox + - grid css + - laioutes css + - ordenação +translation_of: Learn/CSS/CSS_layout/Flexbox +--- +<div> +<p>{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout/Grids", "Learn/CSS/CSS_layout")}}</p> +</div> + +<p class="summary">Uma nova tecnologia, mas com suporte bastante difundido entre navegadores, o Flexbox está se tornando apto para uso geral. Flexbox provê ferramentas para criação rápida de layouts complexos e flexíveis, e características que se mostraram historicamente difíceis com CSS. Este artigo explica todos os seus fundamentos.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Pré-requisitos:</th> + <td>HTML básico (estude <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Introdução a HTML</a>), e uma ideia de como CSS funciona (estude <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introdução a CSS</a>.)</td> + </tr> + <tr> + <th scope="row">Objetivo:</th> + <td>Aprender como usar o sistema de Flexbox layout para criar web layouts.</td> + </tr> + </tbody> +</table> + +<h2 id="Por_quê_Flexbox">Por quê <em>Flexbox</em>?</h2> + +<p>Por um longo tempo, as únicas ferramentas compatíveis entre browsers disponíveis para criação de layouts CSS eram coisas como <a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">floats</a> e <a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">posicionamento</a>. Estas são boas e funcionam, mas em alguns casos também são limitadas e frustrantes.</p> + +<p>Os requisitos de layouts a seguir são difíceis ou impossíveis de se conseguir com estas ferramentas, em qualquer tipo conveniente e flexível:</p> + +<ul> + <li>Centralizar um bloco de conteúdo verticalmente dentro de seu pai.</li> + <li>Fazer com que os filhos de um container ocupe uma quantidade igual de largura/altura disponível, independente da quantidade de largura/altura disponível.</li> + <li>Fazer todas as colunas de um layout com múltiplas colunas adotem a mesma altura, mesmo que contenham uma quantidade diferente de conteúdo.</li> +</ul> + +<p>Como você verá nas seções subsequentes, <em>flexbox</em> faz muitas tarefas de layouts de maneira mais fácil. Vamos nos aprofundar!</p> + +<h2 id="Introduzindo_um_exemplo_simples">Introduzindo um exemplo simples</h2> + +<p>Neste artigo nós vamos trabalhar uma série de exercícios para ajudá-lo a entender como o flexbox funciona. Para começar, você deve fazer uma cópia local do arquivo inicial — <a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/flexbox/flexbox0.html">flexbox0.html</a> do nosso repositório no github — carregue-o em um navegador moderno (como Firefox ou Chrome), e abra o arquivo no seu editor de código. Você pode <a href="http://mdn.github.io/learning-area/css/css-layout/flexbox/flexbox0.html">ver a página aqui</a> também.</p> + +<p>Você verá que temos um elemento {{HTMLElement("header")}} com um cabeçalho no nível superior dentro dele, e um elemento {{HTMLElement("section")}} contendo três {{HTMLElement("article")}}s. Nós vamos usá-los para criar um layout padrão de três colunas.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13406/flexbox-example1.png" style="border-style: solid; border-width: 1px; display: block; height: 324px; margin: 0px auto; width: 800px;"></p> + +<h2 id="Especificando_os_elementos_a_serem_definidos_como_caixas_flex">Especificando os elementos a serem definidos como caixas <em>flex</em></h2> + +<p>Para iniciar, vamos definir quais elementos serão flexible boxes. Para isto, temos que definir um valor especial de {{cssxref("display")}} no elemento pai dos elementos que queremos afetar. neste caso são os elementos {{HTMLElement("article")}}, portanto vamos definir o valor no elemento {{HTMLElement("section")}} (que se torna um flex container):</p> + +<pre class="brush: css">section { + display: flex; +}</pre> + +<p>O resultado disso deve ser algo assim:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13408/flexbox-example2.png" style="border-style: solid; border-width: 1px; display: block; height: 348px; margin: 0px auto; width: 800px;"></p> + +<p>Então, esta única declaração nos dá tudo que precisamos — incrivel, certo? Nós temos um layout de múltiplas com tamanhos iguais, e todas as colunas tem a mesma altura. Isto porque o valor padrão dado aos flex items (os filhos do flex container) são configurados para resolver problemas comuns, como este. Voltaremos a este assunto depois.</p> + +<div class="note"> +<p><strong>Nota</strong>: Você pode definir também ao {{cssxref("display")}} o valor <code>inline-flex</code> se quiser colocar os items em linha como flexible boxes.</p> +</div> + +<h2 id="Um_aparte_no_modelo_flex">Um aparte no modelo <em>flex</em></h2> + +<p>Quando os elementos são definidos como flexibles boxes, eles são dispostos ao longo de dois eixos:</p> + +<p><img alt="flex_terms.png" class="default internal" src="/files/3739/flex_terms.png" style="display: block; margin: 0px auto;"></p> + +<ul> + <li>O <em><strong>main axis</strong></em> é o eixo que corre na direção em que os flex items estão dispostos (por exemplo, as linhas da página, ou colunas abaixo da página.) O início e o fim do eixo é chamado <em><strong>main start</strong></em> e <em><strong>main end</strong></em>.</li> + <li>O <em><strong>cross axis</strong></em> é o eixo perpendicular que corre na direção em que os flex items são dispostos. O início e o fim deste eixo são chamados de <em><strong>cross start</strong></em> e <em><strong>cross end</strong></em>.</li> + <li>O elemento pai que possui <code>display: flex</code> configurado ( {{HTMLElement("section")}} em nosso exemplo) é chamado de <em><strong>flex container</strong></em>.</li> + <li>Os itens iniciados como flexible boxes dentro do flex container são chamados <em><strong>flex items</strong></em> (o {{HTMLElement("article")}} em nosso caso).</li> +</ul> + +<p>Tenha esta terminologia em mente à medida que passar para as seções subsequentes. Você pode voltar a esta referência se ficar confuso quanto aos termos usados inicialmente.</p> + +<h2 id="Colunas_ou_linhas">Colunas ou linhas?</h2> + +<p>Flexbox possui uma propriedade chamada {{cssxref("flex-direction")}} que especifica a direção do eixo principal (em qual direção os filhos da <em>flexbox</em> estarão arranjados) — que por padrão seu valor é <code>row</code> (linha), que faz com que eles fiquem arranjados numa linha na direção que o seu navegador está configurado de acordo com a direção de leitura do seu idioma (da esquerda para a direita, no caso do inglês ou português).</p> + +<p>Experimente adicionar a seguinte declaração na seção de sua regra:</p> + +<pre class="brush: css">flex-direction: column;</pre> + +<p>Você verá que isso organiza os elementos no laioute de coluna, assim como eles estavam antes de adicionarmos qualquer regra CSS. Antes de você seguir, remova essa declaração do seu exemplo.</p> + +<div class="note"> +<p><strong>Nota</strong>: Você também pode arranjar itens flexíveis em direção reversa usando os valores <code>row-reverse</code> e <code>column-reverse</code>. Experimente usar esses valores no seu exemplo também!</p> +</div> + +<h2 id="Embrulhamento">Embrulhamento</h2> + +<p>Um problema que aparece quando você tem uma quantidade fixa de elementos com a mesma largura e altura no seu esquema é que eventualmente seus elementos filhos <em>flexbox</em> irão sobrepor seu elemento pai (<em>container</em>), quebrando o laioute. Dê uma olhada no nosso exemplo <a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/flexbox/flexbox-wrap0.html">flexbox-wrap0.html</a>, e experimente <a href="http://mdn.github.io/learning-area/css/css-layout/flexbox/flexbox-wrap0.html">visualizá-lo online</a> (tenha uma cópia local desse arquivo no seu computador se você quiser continuar acompanhando os exemplos):</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13410/flexbox-example3.png" style="display: block; height: 646px; margin: 0px auto; width: 800px;"></p> + +<p>Aqui vemos que os filhos estão de fato saindo fora do elemento recipiente (<em>container</em>). Uma maneira de consertar isso é adicionando a seguinte declaração na seção de sua regra CSS:</p> + +<pre class="brush: css">flex-wrap: wrap;</pre> + +<p>Experimente isso agora; você verá que o laioute parece muito melhor agora com essa regra:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13412/flexbox-example4.png" style="display: block; height: 646px; margin: 0px auto; width: 800px;">Agora temos várias linhas — tantos elementos filhos <em>flexbox</em> estão encaixados em cada linha quantos fazem sentido, e qualquer sobreposição é movida para a próxima linha. A declaração <code>flex: 200px</code> configurada nos elementos {{htmlelement("article")}} significa que cada um terá pelo menos 200 pixels de largura; discutiremos essa propriedade mais detalhadamente mais tarde. Você também deve notar que os últimos filhos na última linha estão mais largos para que a linha inteira possa ser preenchida.</p> + +<p>Mas ainda tem mais para fazermos com isso. Primeiro, experimente mudar sua propriedade {{cssxref("flex-direction")}} para o valor <code>row-reverse</code> — agora você verá que ainda tem um laioute com várias linhas, mas ele começa no canto oposto da janela do navegador e segue na direção reversa.</p> + +<h2 id="Forma_abreviada_flex-flow">Forma abreviada: <em>flex-flow</em></h2> + +<p>A esta altura vale ressaltar que existe uma abreviação para as regras {{cssxref("flex-direction")}} e {{cssxref("flex-wrap")}}: a {{cssxref("flex-flow")}}. Logo, você pode substituir as seguintes regras</p> + +<pre class="brush: css">flex-direction: row; +flex-wrap: wrap;</pre> + +<p>por</p> + +<pre class="brush: css">flex-flow: row wrap;</pre> + +<h2 id="Dimensionamento_flexível_de_elementos_flex">Dimensionamento flexível de elementos <em>flex</em></h2> + +<p>Vamos agora voltar ao nosso primeiro exemplo, e ver como podemos controlar qual a proporção de espaço os elementos <em>flex</em> pode tomar. Localize sua cópia local do arquivo <a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/flexbox/flexbox0.html">flexbox0.html</a>, ou tenha uma cópia de <a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/flexbox/flexbox1.html">flexbox1.html</a> como um novo ponto de partida (<a href="http://mdn.github.io/learning-area/css/css-layout/flexbox/flexbox1.html">veja online</a>).</p> + +<p>Primeiro adicione a seguinte regra no final do seu CSS:</p> + +<pre class="brush: css">article { + flex: 1; +}</pre> + +<p>Esse é um valor relativo sem unidade que define quanto de espaço disponível pelo eixo principal cada elemento <em>flex</em> pode ter. Neste caso, estamos dando para cada elemento {{HTMLElement("article")}} o valor de 1, que significa que eles terão uma quantidade igual de espaço restante depois de coisas como preenchimento ({{cssxref("padding")}}) e margem ({{cssxref("margin")}})<em> </em>forem definidos. É uma proporção, o que significa que dado que mesmo que você coloque o valor de "400000", para cada elemento <em>flex</em>, terá o mesmo efeito que o valor "1" previamente colocado.</p> + +<p>Agora, adicione a seguinte regra abaixo da última:</p> + +<pre class="brush: css">article:nth-of-type(3) { + flex: 2; +}</pre> + +<p>Assim que você atualizar a página, você verá que o terceiro elemento {{HTMLElement("article")}} ocupa duas vezes mais do espaço disponível que os outros dois — existe agora quatro unidades na proporção total disponível. Os dois primeiros elementos <em>flex</em> tem uma unidade cada, dessa proporção, logo cada um deles ocupam 1/4 do espaço disponível. O terceiro tem 2 unidades, logo ele ocupa 2/4 (ou metade, 1/2) do espaço disponível. </p> + +<p>Você também pode especificar um valor de tamanho mínimo para a regra <em>flex</em>. Experimente atualizar a regra para o {{HTMLElement("article")}} existente para que fique assim:</p> + +<pre class="brush: css">article { + flex: 1 200px; +} + +article:nth-of-type(3) { + flex: 2 200px; +}</pre> + +<p>Isso basicamente diz o seguinte: "Para cada elemento <em>flex</em> primeiro será dado 200px do espaço disponível. Depois, o restante do espaço disponível será distribuído entre os elementos, de acordo com a unidade de proporção definida.". Atualize a página e você verá a diferença de como o espaço é distribuído.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13406/flexbox-example1.png" style="border-style: solid; border-width: 1px; display: block; height: 324px; margin: 0px auto; width: 800px;"></p> + +<p>O valor real de cada caixa <em>flex</em> pode ser visto pela sua flexibilidade/responsividade — se você redimensionar a janela do navegador, ou adicionar outro elemento {{HTMLElement("article")}}, o laioute continua funcionando sem quebrar.</p> + +<h2 id="flex_Forma_abreviada_ou_forma_normal"><em>flex</em>: Forma abreviada ou forma normal?</h2> + +<p>{{cssxref("flex")}} é uma propriedade abreviada que pode especificar até três valores diferentes:</p> + +<ul> + <li>O valor de proporção sem unidade que falamos sobre ele acima. Ele também pode ser especificado individualmente usando a regra {{cssxref("flex-grow")}}.</li> + <li>Um segundo valor de proporção sem unidade — {{cssxref("flex-shrink")}} — que convém ser usado quando os elementos <em>flex</em> estão sobrepondo a elemento recipiente (<em>container</em>). Este especifica qual a quantidade será retirada do tamanho de cada elemento <em>flex</em>, para que ele não ultrapasse o valor do elemento recipiente (<em>container</em>). Esta é uma funcionalidade bem avançada do <em>flexbox</em>, e não será abordada neste artigo.</li> + <li>O valor mínimo para o tamanho que discutimos acima. Este pode ser especificado individualmente usando a regra {{cssxref("flex-basis")}}.</li> +</ul> + +<p>Aconselhamos usar sempre a forma abreviada a menos que você precise usar a regra normal (por exemplo para sobrescrever algum valor pré-definido). As regras normais, isto é não abreviadas, geram muito mais código e podem gerar confusão.</p> + +<h2 id="Alinhamento_Horizontal_e_Vertical">Alinhamento Horizontal e Vertical</h2> + +<p>Você também pode usar as funcionalidade do <em>flexbox</em> para alinhar elementos no eixo principal ou no eixo transversal (relembre esse assunto na seção <a href="/pt-BR/docs/Learn/CSS/CSS_layout/Flexbox#Um_aparte_no_modelo_flex">Um aparte no modelo flex</a>). Vamos explorar isso olhando para um outro exemplo — <a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/flexbox/flex-align0.html">flex-align0.html</a> (<a href="http://mdn.github.io/learning-area/css/css-layout/flexbox/flex-align0.html">veja online</a>) — o qual vamos transformá-lo num botão/barra de ferramentas bem feito e flexível. Neste momento você verá uma barra de menu horizontal, com alguns botões expremidos no canto superior esquerdo:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13414/flexbox-example5.png" style="display: block; height: 77px; margin: 0px auto; width: 600px;"></p> + +<p>Primeiro, tenha uma cópia local desse exemplo.</p> + +<p>Agora, adicione o seguinte trecho ao final do CSS no arquivo do exemplo:</p> + +<pre class="brush: css">div { + display: flex; + align-items: center; + justify-content: space-around; +}</pre> + +<p>Atualize a página e você verá que os botões estão agora bem arranjados no centro, horizontalmente e verticalmente. Fizemos isso através de duas novas propriedades.</p> + +<div class="note"> +<p><strong>Nota</strong>: Nesse exemplo, o eixo principal é representado horizontalmente e o eixo transversal é o vertical.</p> +</div> + +<p>{{cssxref("align-items")}} controla onde os elementos <em>flex</em> ficam no eixo transversal:</p> + +<ul> + <li>Por padrão, seu valor é <code>stretch</code>, que estica todos os elementos <em>flex</em> para preencher o elemento pai na direção do eixo transversal. Se o elemento pai não tem largura fixa na direção do eixo transversal, então todos os elementos <em>flex</em> esticarão até o mais comprido dos elementos <em>flex</em>. Foi assim que o nosso primeiro exemplo ficou com colunas de mesma altura por padrão.</li> + <li>O valor <code>center</code> que usamos no exemplo acima, faz com que os elementos mantenham suas dimensões intrínsecas, mas que seja centralizados ao longo do eixo transversal. É por isso que os botões do nosso exemplo atual estão centralizados verticalmente.</li> + <li>Você também pode colocar valores como <code>flex-start</code> e <code>flex-end</code>, os quais alinharão todos os elementos no início ou fim do eixo transversal, respectivamente. Veja {{cssxref("align-items")}} para maiores detalhes.</li> +</ul> + +<p>Você pode sobrescrever o comportamento de {{cssxref("align-items")}} para elementos individuais, usando a regra {{cssxref("align-self")}} nesses elementos. Por exemplo, experimente adicionar o seguinte trecho no seu CSS:</p> + +<pre class="brush: css">button:first-child { + align-self: flex-end; +}</pre> + +<p>Veja qual efeito isso dá, e remova novamente quando terminar.</p> + +<p>{{cssxref("justify-content")}} controla onde os elementos <em>flex</em> ficam no eixo principal.</p> + +<ul> + <li>O valor padrão é <code>flex-start</code>, que faz com que todos os elementos estejam no início do eixo principal.</li> + <li>Você pode usar <code>flex-end</code> para que eles fiquem no final.</li> + <li><code>center</code> também é um valor para {{cssxref("justify-content")}}, e fará com que os elementos <em>flex</em> fiquem no centro do eixo principal.</li> + <li>O valor que usamos acima, <code>space-around</code>, é útil pois ele distribui todos os elementos igualmente pelo eixo principal, com um pouquinho de espaço no final.</li> + <li>Existe um outro valor, <code>space-between</code>, o qual é muito similar ao <code>space-around</code>, exceto que ele não deixa nenhum espaço no final.</li> +</ul> + +<p>Nós sugerimos que você brinque um pouco mais com essas regras e seus valores para ver como funcionam ainda mais, antes de seguir nos estudos.</p> + +<h2 id="Ordenação_de_elementos_flex">Ordenação de elementos <em>flex</em></h2> + +<p>O <em>flexbox</em> também tem uma funcionalidade para alteração da ordem dos elementos <em>flex</em> no laioute, sem afetar a ordem no código fonte HTML. Esta é mais uma coisa que é impossível fazer nos métodos tradicionais de esquema de laioutes.</p> + +<p>O código para fazer isso é bem simples: experimente adicionar o seguinte CSS ao final do código do exemplo da barra de botões:</p> + +<pre class="brush: css">button:first-child { + order: 1; +}</pre> + +<p>Atualize seu navegador, você verá que o botão "<em>Smile</em>" foi movido para o final do eixo principal. Vamos falar sobre como isso funciona com mais detalhes:</p> + +<ul> + <li>Por padrão, todos os elementos <em>flex</em> possuem uma propriedade {{cssxref("order")}} com valor 0 (zero).</li> + <li>Elementos <em>flex</em> com valores maiores de {{cssxref("order")}}, aparecerão depois na tela, do que elementos com valores menores, os quais aparecem antes.</li> + <li>Elementos <em>flex</em> com o mesmo valor aparecerão de acordo com a ordem que possuem no documento HTML. Logo, se você tiver quatro elementos com os seguintes valores para {{cssxref("order")}}: 2, 1, 1 e 0, eles aparecerão na tela na seguinte ordem: 4º, 2º, 3º e 1º elemento, respectivamente.</li> + <li>O 3º elemento aparece depois do 2º pois ele tem o mesmo valor para {{cssxref("order")}} mas está definido depois no documento fonte.</li> +</ul> + +<p>Você também pode usar valores negativos para fazer elementos aparecerem antes do(s) elemento(s) definidos com {{cssxref("order")}} 0 (zero). Por exemplo, Você poderia fazer com que o botão "<em>Blush</em>" aparecesse no começo do eixo principal (horizontal), usando a seguinte regra:</p> + +<pre class="brush: css">button:last-child { + order: -1; +}</pre> + +<h2 id="Elementos_flex_aninhados">Elementos <em>flex</em> aninhados</h2> + +<p>É possível criar laioutes bem complexos com <em>flexbox</em>. É perfeitamente aceitável configurar um elemento <em>flex</em> para também ser um <em>container</em>, para que seus filhos também se comportem como caixas <em>flex</em>. Dê uma olhada em <a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/flexbox/complex-flexbox.html">complex-flexbox.html</a> (<a href="http://mdn.github.io/learning-area/css/css-layout/flexbox/complex-flexbox.html">veja também online</a>).</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13418/flexbox-example7.png" style="border-style: solid; border-width: 1px; display: block; margin: 0px auto;"></p> + +<p>O HTML desse exemplo é relativamente simples. Temos um elemento {{HTMLElement("section")}} contendo três {{HTMLElement("article")}}. O terceiro desses {{HTMLElement("article")}} contém três elementos {{HTMLElement("div")}}:</p> + +<pre>section - article + article + article - div - button + div button + div button + button + button</pre> + +<p>Vamos dar uma olhada no código que usamos no laioute.</p> + +<p>Primeiro, configuramos para que os filhos da {{HTMLElement("section")}} se arranjem como elementos <em>flex</em>.</p> + +<pre class="brush: css">section { + display: flex; +}</pre> + +<p>Em seguida, configuramos alguns valores <em>flex</em> nos próprios elementos {{HTMLElement("article")}}. Veja especialmente a segunda regra aqui — estamos configurando para que o terceiro {{HTMLElement("article")}} tenha seus filhos arranjados como elementos <em>flex</em> também, mas desta vez eles estarão dispostos em coluna.</p> + +<pre class="brush: css">article { + flex: 1 200px; +} + +article:nth-of-type(3) { + flex: 3 200px; + display: flex; + flex-flow: column; +} +</pre> + +<p>Depois, selecionamos o primeiro elemento {{HTMLElement("div")}}. Primeiro usamos <code>flex:1 100px;</code> para efetivamente dar a ele a altura de 100px, depois configuramos para que seus filhos (os elementos {{HTMLElement("button")}}) se arranjem como elementos <em>flex</em>. Aqui, nós os arranjamos em uma linha que os envolvem, e os alinhamos no centro do espaço disponível, como fizemos no exemplo do botão individual que vimos anteriormente:</p> + +<pre class="brush: css">article:nth-of-type(3) div:first-child { + flex:1 100px; + display: flex; + flex-flow: row wrap; + align-items: center; + justify-content: space-around; +}</pre> + +<p>Finalmente, configuramos alguns tamanhos no botão, mas o mais interessante é que demos a ele o valor 1 para a propriedade <em>flex</em>. Isso dá um resultado interessante, que você verá se redimensionar a largura da janela do seu navegador. Esses botões tomarão o máximo de espaço que puderem e ficarão ao máximo na mesma linha, se puderem, mas quando não puderem mais caber na mesma linha, os que estão muito apertados irão para novas linhas de forma que o laioute não quebre e o conteúdo ainda esteja legível ao usuário.</p> + +<pre class="brush: css">button { + flex: 1; + margin: 5px; + font-size: 18px; + line-height: 1.5; +}</pre> + +<h2 id="Compatibilidade_entre_navegadores">Compatibilidade entre navegadores</h2> + +<p>O suporte a f<em>lexbox</em> está disponível nos navegadores mais novos — Firefox, Chrome, Opera, Microsoft Edge e IE 11, nas versões mais novas do Android e iOS, etc.<br> + Contudo você deve estar ciente que ainda existem navegadores antigos em uso que não suportam a regra <em>flexbox</em> (ou até suportam, mas numa versão desatualizada).</p> + +<p>Enquanto você está apenas aprendendo ou testando, a compatibilidade entre navegadores não importa muito; no entanto se você pretende usar o <em>flexbox</em> num site de verdade, você precisa fazer testes e certificar que a experiência do usuário é aceitável em qualquer navegador possível.</p> + +<p><em>Flexbox</em> é um pouco mais ardiloso que algumas propriedades CSS. Por exemplo, se o suporte a sombras de CSS falta num browser, é muito menos provável de comprometer a usabilidade, afinal apenas as sombras dos elementos que não estarão aparecendo. Contudo, a falta de suporte à propriedade <em>flexbox</em> pode quebrar o laioute do seu site, e comprometer a sua usabilidade.</p> + +<p>Iremos discutir estratégias para contornar problemas complicados de compatibilidade entre navegadores num módulo futuro.</p> + +<h2 id="Sumário">Sumário</h2> + +<p>Isso conclui nosso tour sobre o básico de <em>flexbox</em>. Esperamos que você tenha aproveitado, e que você continue aproveitando enquanto avança com seu aprendizado.<br> + No próximo tópico, veremos outro aspecto importante dos Esquemas em CSS: os sistemas de <em>grid, </em>como você pode ver nesse artigo sobre <a href="https://blog.alura.com.br/criando-layouts-com-css-grid-layout/">CSS grid layout</a>.</p> + +<div>{{PreviousMenuNext("Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout/Grids", "Learn/CSS/CSS_layout")}}</div> + +<div> +<h2 id="Neste_módulo">Neste módulo</h2> + +<ul> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Introduction">Introdução a Esquemas CSS</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">Flutuando Elementos com "float"</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">Posicionamento de elementos</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Practical_positioning_examples">Exemplos práticos de posicionamento</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grids</a></li> +</ul> +</div> diff --git a/files/pt-br/learn/css/css_layout/fluxo_normal/index.html b/files/pt-br/learn/css/css_layout/fluxo_normal/index.html new file mode 100644 index 0000000000..c27a403fa7 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/fluxo_normal/index.html @@ -0,0 +1,95 @@ +--- +title: Fluxo Normal +slug: Learn/CSS/CSS_layout/Fluxo_Normal +translation_of: Learn/CSS/CSS_layout/Normal_Flow +--- +<div>{{LearnSidebar}}</div> + +<p>{{PreviousMenuNext("Learn/CSS/CSS_layout/Introduction", "Learn/CSS/CSS_layout/Flexbox", "Learn/CSS/CSS_layout")}}</p> + +<p class="summary">Este artigo aborda o <em>Fluxo Normal</em> de alinhamento e acomodação do conteúdo de uma página HTML, na qual o desenvolvedor não inseriu estilos pessoais. Este fluxo é um padrão usado pelos navegodares web. É uma solução preguiçosa ou rápida. Se o <em>Fluxo Normal</em> por ventura não desagradar o programador, poupado será o seu tempo e esforço. Com o ônus adiado para quando ele quiser algo diferente.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Prerrequisitos:</th> + <td>Introdução ao HTML (study <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Introduction to HTML</a>), e uma noção de como o CSS funciona (study <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introduction to CSS</a>.)</td> + </tr> + <tr> + <th scope="row">Objectivo:</th> + <td>Explicar qual é o leiaute padrão aplicado pelos navegadores web - a um arquivo HTML - sempre que não houver estilo ou formatos definidos pelo desenvolvedor da referida página.</td> + </tr> + </tbody> +</table> + +<p>Conforme detalhado na última lição de introdução ao leiaute, os elementos em uma página da web acomodam-se em Fluxo Normal, quando não é aplicada qualquer regra CSS para alterar a maneira como estes se comportam. And, as we began to discover, you can change how elements behave either by adjusting their position in that normal flow, or removing them from it altogether. Starting with a solid, well-structured document that is readable in normal flow is the best way to begin any webpage. It ensures that your content is readable, even if the user is using a very limited browser or a device such as a screen reader that reads out the content of the page. In addition, as normal flow is designed to make a readable document, by starting in this way you are working with the document rather than fighting against it as you make changes to the layout.</p> + +<p>Before digging deeper into different layout methods, it is worth revisiting some of the things you will have studied in previous modules with regard to normal document flow.</p> + +<h2 id="How_are_elements_laid_out_by_default">How are elements laid out by default?</h2> + +<p>First of all, individual element boxes are laid out by taking the elements' content, then adding any padding, border and margin around them — it's that box model thing again, which we've looked at earlier.</p> + +<p>By default, a <a href="/en-US/docs/Web/HTML/Block-level_elements">block level element</a>'s content is 100% of the width of its parent element, and as tall as its content. <a href="/en-US/docs/Web/HTML/Inline_elements">Inline elements</a> are as tall as their content, and as wide as their content. You can't set width or height on inline elements — they just sit inside the content of block level elements. If you want to control the size of an inline element in this manner, you need to set it to behave like a block level element with <code>display: block;</code> (or even,<code>display: inline-block;</code> which mixes characteristics from both.)</p> + +<p>That explains individual elements, but what about how elements interact with one another? The normal layout flow (mentioned in the layout introduction article) is the system by which elements are placed inside the browser's viewport. By default, block-level elements are laid out in the <em>block flow direction</em>, based on the parent's <a href="/en-US/docs/Web/CSS/writing-mode">writing mode</a> (<em>initial</em>: horizontal-tb) — each one will appear on a new line below the last one, and they will be separated by any margin that is set on them. In English therefore, or any other horizontal, top to bottom writing mode, block-level elements are laid out vertically.</p> + +<p>Inline elements behave differently — they don't appear on new lines; instead, they sit on the same line as one another and any adjacent (or wrapped) text content, as long as there is space for them to do so inside the width of the parent block level element. If there isn't space, then the overflowing text or elements will move down to a new line.</p> + +<p>If two adjacent elements both have the margin set on them and the two margins touch, the larger of the two remains, and the smaller one disappears — this is called margin collapsing, and we have met this before too.</p> + +<p>Let's look at a simple example that explains all of this:</p> + +<div id="Normal_Flow"> +<pre class="brush: html"><h1>Basic document flow</h1> + +<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> + +<p>By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p> + +<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> + +<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements will <span>wrap onto a new line if possible (like this one containing text)</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; +} + +p { + background: rgba(255,84,104,0.3); + border: 2px solid rgb(255,84,104); + padding: 10px; + margin: 10px; +} + +span { + background: white; + border: 1px solid black; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Normal_Flow', '100%', 500) }}</p> + +<h2 id="Summary">Summary</h2> + +<p>Now that you understand normal flow, and how the browser lays things out by default, move on to understand how to change this default display to create the layout needed by your design.</p> + +<p>{{PreviousMenuNext("Learn/CSS/CSS_layout/Introduction", "Learn/CSS/CSS_layout/Flexbox", "Learn/CSS/CSS_layout")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Introduction">Introduction to CSS layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Normal_Flow">Normal flow</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grid</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">Floats</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">Positioning</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout">Multiple-column layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design">Responsive design</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Media_queries">Beginner's guide to media queries</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods">Legacy layout methods</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Supporting_Older_Browsers">Supporting older browsers</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension">Fundamental layout comprehension assessment</a></li> +</ul> diff --git a/files/pt-br/learn/css/css_layout/index.html b/files/pt-br/learn/css/css_layout/index.html new file mode 100644 index 0000000000..18740f1b03 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/index.html @@ -0,0 +1,69 @@ +--- +title: CSS layout +slug: Learn/CSS/CSS_layout +tags: + - Beginner + - CSS + - Floating + - Grids + - Guide + - Landing + - Layout + - Learn + - Module + - Multiple column + - NeedsTranslation + - Positioning + - TopicStub + - flexbox + - float +translation_of: Learn/CSS/CSS_layout +--- +<div>{{LearnSidebar}}</div> + +<p class="summary">Até esse ponto nós já vimos fundamentos do CSS, como estilizar textos, e como estilizar e manipular os blocos que envolvem o conteúdo. Chegou a hora de ver como posicionar seus blocos no lugar certo tendo como referência o viewport ou outro elemento. Cobrimos os pré-requisitos necessários para que possamos ir mais a fundo no layout CSS, veremos diferentes configurações de exibição, métodos tradicionais de layout envolvendo float e posicionamento, e ferramentas modernas de layout como flexbox.</p> + +<h2 id="Prerequisitos">Prerequisitos</h2> + +<p>Antes de iniciar esse modulo, você precisa:</p> + +<ol> + <li>Ter um conhecimento básico de HTML, como discutido no módulo <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Introdução ao HTML</a>.</li> + <li>Estar confortável com os fundamentos do CSS, como discutido em <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introdução ao CSS</a>.</li> + <li>Entender como <a href="/en-US/docs/Learn/CSS/Styling_boxes">estilizar blocos</a>.</li> +</ol> + +<div class="note"> +<p><strong>Nota</strong>: Se você estiver trabalhando em um computador/tablete/outro dispositivo em que você não possa criar seus próprios arquivos, você pode testar (muitos dos) os códigos de exemplo em um programa de códigos online como o <a href="http://jsbin.com/">JSBin</a> ou <a href="https://thimble.mozilla.org/">Thimble</a>.</p> +</div> + +<h2 id="Guias">Guias</h2> + +<p>Esse artigo ira introduzir as ferramentas fundamentais para o layout e as técnicas disponiveis no CSS.</p> + +<dl> + <dt><a href="/en-US/docs/Learn/CSS/CSS_layout/Introduction">Introdução ao CSS</a></dt> + <dd>Este artigo recapitulará alguns dos recursos de layout CSS que já abordamos em módulos anteriores — como diferentes valores {{cssxref("display")}} — e apresentará alguns dos conceitos que abordaremos ao longo deste módulo.</dd> +</dl> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Normal_Flow">Fluxo normal</a></dt> + <dd>Os elementos das páginas web apresentam-se de acordo com o fluxo normal (até que façamos algo para mudar isso). Este artigo explica os fundamentos do fluxo normal, bem como uma base para aprender como alterá-lo.</dd> + <dt><a href="https://developer.mozilla.org/pt-BR/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a></dt> + <dd>É um método para criar layout unidimensional, renderizando itens em linhas ou colunas. Os itens flexíveis preenchem os espaços pondendo encolher para caberem em espaços menores. Este artigo explica todos os fundamentos.</dd> + <dt><a href="https://developer.mozilla.org/pt-BR/docs/Learn/CSS/CSS_layout/Flexbox">Grids</a></dt> + <dd>CSS Grid layout é um sistema de layout bidimensional para páginas web. Ele permite que você coloque conteúdo em linhas e colunas. Tem muitos recursos que facilitam a criação de layouts complexos. Este artigo fornecerá tudo o que você precisa saber para começar a usar Grid layout em suas páginas.</dd> +</dl> + +<dl> + <dt><a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">Floats</a></dt> + <dd>Originalmente para imagens flutuantes em blocos de texto, a propriedade {{cssxref("float")}} tornou-se uma das ferramentas mais usadas para criar layouts de várias colunas em páginas web. Com o advento do Flexbox e do Grid o Flot retorna ao seu propósto original. Este artigo explica tudo.</dd> + <dt><a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">Posicionamento</a></dt> + <dd>O posicionamento permite retirar elementos do fluxo normal do layout do documento fazendo com que se comportem de maneira diferente, por exemplo, posicionando-se um em cima do outro ou permanecendo numa posição fixa no navegador. Este artigo explica os diferentes valores de {{cssxref("position")}} e como usá-los.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout">Layout de múltiplas colunas</a></dt> + <dd>A especificação de layout de várias colunas fornece um método para colocar conteúdo em colunas, como nos jornais. Este artigo explicará como usar este recurso.</dd> + <dt><a href="/en-US/docs/Learn/CSS/CSS_layout/Practical_positioning_examples">Exemplos práticos de posicionamento</a></dt> + <dd>Com as noções básicas de posicionamento abordadas no último artigo, veremos agora a construção de alguns exemplos do mundo real, para ilustrar que tipos de coisas você pode fazer com o posicionamento.</dd> + <dt><a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grids</a></dt> + <dd>Os sistemas de Grid são outro recurso muito comum usado nos layouts de CSS, que tendem a ser implementados usando flutuadores ou outros recursos de layout. Você imagina seu layout como um número definido de colunas (por exemplo, 4, 6 ou 12) e ajusta suas colunas de conteúdo dentro dessas colunas imaginárias. Neste artigo, exploraremos a idéia básica por trás da criação de um sistema de grade, examinaremos o uso de um sistema de grade pronto fornecido por uma estrutura de grade e terminaremos com a experiência com CSS Grids - um novo recurso de navegador que torna a implementação do design de grade em a Web muito mais fácil.</dd> +</dl> diff --git a/files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html b/files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html new file mode 100644 index 0000000000..9314e8efd3 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html @@ -0,0 +1,707 @@ +--- +title: Introdução ao leiaute com CSS +slug: Learn/CSS/CSS_layout/Intro_leiaute_CSS +translation_of: Learn/CSS/CSS_layout/Introduction +--- +<div>{{LearnSidebar}}</div> + +<div>{{NextMenu("Learn/CSS/CSS_layout/Normal_Flow", "Learn/CSS/CSS_layout")}}</div> + +<p class="summary">This article will recap some of the CSS layout features we've already touched upon in previous modules — such as different {{cssxref("display")}} values — and introduce some of the concepts we'll be covering throughout this module.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Prerequisites:</th> + <td>The basics of HTML (study <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Introduction to HTML</a>), and an idea of How CSS works (study <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introduction to CSS</a>.)</td> + </tr> + <tr> + <th scope="row">Objective:</th> + <td>To give you an overview of CSS page layout techniques. Each technique can be learned in greater detail in subsequent tutorials.</td> + </tr> + </tbody> +</table> + +<p>CSS page layout techniques allow us to take elements contained in a web page and control where they are positioned relative to their default position in normal layout flow, the other elements around them, their parent container, or the main viewport/window. The page layout techniques we'll be covering in more detail in this module are</p> + +<ul> + <li>Normal flow</li> + <li>The {{cssxref("display")}} property</li> + <li>Flexbox</li> + <li>Grid</li> + <li>Floats</li> + <li>Positioning</li> + <li>Table layout</li> + <li>Multiple-column layout</li> +</ul> + +<p>Each technique has its uses, advantages, and disadvantages, and no technique is designed to be used in isolation. By understanding what each method is designed for you will be in a good place to understand which is the best layout tool for each task.</p> + +<h2 id="Normal_flow">Normal flow</h2> + +<p>Normal flow is how the browser lays out HTML pages by default when you do nothing to control page layout. Let's look at a quick HTML example:</p> + +<pre class="brush: html"><p>I love my cat.</p> + +<ul> + <li>Buy cat food</li> + <li>Exercise</li> + <li>Cheer up friend</li> +</ul> + +<p>The end!</p></pre> + +<p>By default, the browser will display this code as follows:</p> + +<p>{{ EmbedLiveSample('Normal_flow', '100%', 200) }}</p> + +<p>Note here how the HTML is displayed in the exact order in which it appears in the source code, with elements stacked up on top of one another — the first paragraph, followed by the unordered list, followed by the second paragraph.</p> + +<p>The elements that appear one below the other are described as <em>block</em> elements, in contrast to <em>inline</em> elements, which appear one beside the other, like the individual words in a paragraph.</p> + +<div class="note"> +<p><strong>Note</strong>: The direction in which block element contents are laid out is described as the Block Direction. The Block Direction runs vertically in a language such as English, which has a horizontal writing mode. It would run horizontally in any language with a Vertical Writing Mode, such as Japanese. The corresponding Inline Direction is the direction in which inline contents (such as a sentence) would run.</p> +</div> + +<p>When you use CSS to create a layout, you are moving the elements away from the normal flow, but for many of the elements on your page the normal flow will create exactly the layout you need. This is why starting with a well-structured HTML document is so important, as you can then work with the way things are laid out by default rather than fighting against it.</p> + +<p>The methods that can change how elements are laid out in CSS are as follows:</p> + +<ul> + <li><strong>The {{cssxref("display")}} property</strong> — Standard values such as <code>block</code>, <code>inline</code> or <code>inline-block</code> can change how elements behave in normal flow (see <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Box_model#Types_of_CSS_boxes">Types of CSS boxes</a> for more information). We then have entire layout methods that are switched on via a value of <code>display</code>, for example <a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">CSS Grid</a> and <a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a>.</li> + <li><strong>Floats</strong> — Applying a {{cssxref("float")}} value such as <code>left</code> can cause block level elements to wrap alongside one side of an element, like the way images sometimes have text floating around them in magazine layouts.</li> + <li><strong>The {{cssxref("position")}} property</strong> — Allows you to precisely control the placement of boxes inside other boxes. <code>static</code> positioning is the default in normal flow, but you can cause elements to be laid out differently using other values, for example always fixed to the top left of the browser viewport.</li> + <li><strong>Table layout</strong> — features designed for styling the parts of an HTML table can be used on non-table elements using <code>display: table</code> and associated properties.</li> + <li><strong>Multi-column layout</strong> — The <a href="/en-US/docs/Web/CSS/CSS_Columns">Multi-column layout</a> properties can cause the content of a block to layout in columns, as you might see in a newspaper.</li> +</ul> + +<h2 id="The_display_property">The display property</h2> + +<p>The main methods of achieving page layout in CSS are all values of the <code>display</code> property. This property allows us to change the default way something displays. Everything in normal flow has a value of <code>display</code>, used as the default way that elements they are set on behave. For example, the fact that paragraphs in English display one below the other is due to the fact that they are styled with <code>display: block</code>. If you create a link around some text inside a paragraph, that link remains inline with the rest of the text, and doesn’t break onto a new line. This is because the {{htmlelement("a")}} element is <code>display: inline</code> by default.</p> + +<p>You can change this default display behavior. For example, the {{htmlelement("li")}} element is <code>display: block</code> by default, meaning that list items display one below the other in our English document. If we change the display value to <code>inline</code> they now display next to each other, as words would do in a sentence. The fact that you can change the value of <code>display</code> for any element means that you can pick HTML elements for their semantic meaning, without being concerned about how they will look. The way they look is something that you can change.</p> + +<p>In addition to being able to change the default presentation by turning an item from <code>block</code> to <code>inline</code> and vice versa, there are some bigger layout methods that start out as a value of <code>display</code>. However, when using these, you will generally need to invoke additional properties. The two values most important for our purposes when discussing layout are <code>display: flex</code> and <code>display: grid</code>.</p> + +<h2 id="Flexbox">Flexbox</h2> + +<p>Flexbox is the short name for the <a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout">Flexible Box Layout</a> Module, designed to make it easy for us to lay things out in one dimension — either as a row or as a column. To use flexbox, you apply <code>display: flex</code> to the parent element of the elements you want to lay out; all its direct children then become flex items. We can see this in a simple example.</p> + +<p>The HTML markup below gives us a containing element, with a class of <code>wrapper</code>, inside which are three {{htmlelement("div")}} elements. By default these would display as block elements, below one another, in our English language document.</p> + +<p>However, if we add <code>display: flex</code> to the parent, the three items now arrange themselves into columns. This is due to them becoming <em>flex items</em> and being affected by some initial values that flexbox sets on the flex container. They are displayed in a row, because the initial value of {{cssxref("flex-direction")}} set on their parent is <code>row</code>. They all appear to stretch to the height of the tallest item, because the initial value of the {{cssxref("align-items")}} property set on their parent is <code>stretch</code>. This means that the items stretch to the height of the flex container, which in this case is defined by the tallest item. The items all line up at the start of the container, leaving any extra space at the end of the row.</p> + +<div id="Flex_1"> +<div class="hidden"> +<h6 id="Flexbox_Example_1">Flexbox Example 1</h6> + +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper > div { + border-radius: 5px; + background-color: rgb(207,232,220); + padding: 1em; +} + </pre> +</div> + +<pre class="brush: css">.wrapper { + display: flex; +} +</pre> + +<pre class="brush: html"><div class="wrapper"> + <div class="box1">One</div> + <div class="box2">Two</div> + <div class="box3">Three</div> +</div> +</pre> +</div> + +<p>{{ EmbedLiveSample('Flex_1', '300', '200') }}</p> + +<p>In addition to the above properties that can be applied to the flex container, there are properties that can be applied to the flex items. These properties, among other things, can change the way that the items flex, enabling them to expand and contract to fit into the available space.</p> + +<p>As a simple example of this, we can add the {{cssxref("flex")}} property to all of our child items, with a value of <code>1</code>. This will cause all of the items to grow and fill the container, rather than leaving space at the end. If there is more space then the items will become wider; if there is less space they will become narrower. In addition, if you add another element to the markup the items will all become smaller to make space for it — they will adjust size to take up the same amount of space, whatever that is.</p> + +<div id="Flex_2"> +<div class="hidden"> +<h6 id="Flexbox_Example_2">Flexbox Example 2</h6> + +<pre class="brush: css"> * {box-sizing: border-box;} + + .wrapper > div { + border-radius: 5px; + background-color: rgb(207,232,220); + padding: 1em; + } + </pre> +</div> + +<pre class="brush: css">.wrapper { + display: flex; +} + +.wrapper > div { + flex: 1; +} +</pre> + +<pre class="brush: html"><div class="wrapper"> + <div class="box1">One</div> + <div class="box2">Two</div> + <div class="box3">Three</div> +</div> +</pre> +</div> + +<p>{{ EmbedLiveSample('Flex_2', '300', '200') }}</p> + +<div class="note"> +<p><strong>Note</strong>: This has been a very short introduction to what is possible in Flexbox, to find out more, see our <a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a> article.</p> +</div> + +<h2 id="Grid_Layout">Grid Layout</h2> + +<p>While flexbox is designed for one-dimensional layout, Grid Layout is designed for two dimensions — lining things up in rows and columns.</p> + +<p>Once again, you can switch on Grid Layout with a specific value of display — <code>display: grid</code>. The below example uses similar markup to the flex example, with a container and some child elements. In addition to using <code>display: grid</code>, we are also defining some row and column tracks on the parent using the {{cssxref("grid-template-rows")}} and {{cssxref("grid-template-columns")}} properties respectively. We've defined three columns each of <code>1fr</code> and two rows of <code>100px</code>. I don’t need to put any rules on the child elements; they are automatically placed into the cells our grid has created.</p> + +<div id="Grid_1"> +<div class="hidden"> +<h6 id="Grid_example_1">Grid example 1</h6> + +<pre class="brush: css"> * {box-sizing: border-box;} + + .wrapper > div { + border-radius: 5px; + background-color: rgb(207,232,220); + padding: 1em; + } + </pre> +</div> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: 1fr 1fr 1fr; + grid-template-rows: 100px 100px; + grid-gap: 10px; +} +</pre> + +<pre class="brush: html"><div class="wrapper"> + <div class="box1">One</div> + <div class="box2">Two</div> + <div class="box3">Three</div> + <div class="box4">Four</div> + <div class="box5">Five</div> + <div class="box6">Six</div> +</div> +</pre> +</div> + +<p>{{ EmbedLiveSample('Grid_1', '300', '330') }}</p> + +<p>Once you have a grid, you can explicitly place your items on it, rather than relying on the auto-placement behavior seen above. In the second example below we have defined the same grid, but this time with three child items. We've set the start and end line of each item using the {{cssxref("grid-column")}} and {{cssxref("grid-row")}} properties. This causes the items to span multiple tracks.</p> + +<div id="Grid_2"> +<div class="hidden"> +<h6 id="Grid_example_2">Grid example 2</h6> + +<pre class="brush: css"> * {box-sizing: border-box;} + + .wrapper > div { + border-radius: 5px; + background-color: rgb(207,232,220); + padding: 1em; + } + </pre> +</div> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: 1fr 1fr 1fr; + grid-template-rows: 100px 100px; + grid-gap: 10px; +} + +.box1 { + grid-column: 2 / 4; + grid-row: 1; +} + +.box2 { + grid-column: 1; + grid-row: 1 / 3; +} + +.box3 { + grid-row: 2; + grid-column: 3; +} +</pre> + +<pre class="brush: html"><div class="wrapper"> + <div class="box1">One</div> + <div class="box2">Two</div> + <div class="box3">Three</div> +</div> +</pre> +</div> + +<p>{{ EmbedLiveSample('Grid_2', '300', '330') }}</p> + +<div class="note"> +<p><strong>Note</strong>: These two examples are just a small part of the power of Grid layout; to find out more see our <a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grid Layout</a> article.</p> +</div> + +<p>The rest of this guide covers other layout methods, which are less important for the main layout structures of your page but can still help you achieve specific tasks. By understanding the nature of each layout task, you will soon find that when you look at a particular component of your design the type of layout best suited to it will often be clear.</p> + +<h2 id="Floats">Floats</h2> + +<p>Floating an element changes the behavior of that element and the block level elements that follow it in normal flow. The element is moved to the left or right and removed from normal flow, and the surrounding content floats around the floated item.</p> + +<p>The {{cssxref("float")}} property has four possible values:</p> + +<ul> + <li><code>left</code> — Floats the element to the left.</li> + <li><code>right</code> — Floats the element to the right.</li> + <li><code>none</code> — Specifies no floating at all. This is the default value.</li> + <li><code>inherit</code> — Specifies that the value of the <code>float</code> property should be inherited from the element's parent element.</li> +</ul> + +<p>In the example below we float a <code><div></code> left, and give it a {{cssxref("margin")}} on the right to push the text away from the element. This gives us the effect of text wrapped around that box, and is most of what you need to know about floats as used in modern web design.</p> + +<div id="Float_1"> +<div class="hidden"> +<h6 id="Floats_example">Floats example</h6> + +<pre class="brush: css">body { + width: 90%; + max-width: 900px; + margin: 0 auto; +} + +p { + line-height: 2; + word-spacing: 0.1rem; +} + +.box { + background-color: rgb(207,232,220); + border: 2px solid rgb(79,185,227); + padding: 10px; + border-radius: 5px; +} +</pre> +</div> + +<pre class="brush: html"><h1>Simple float example</h1> + +<div class="box">Float</div> + +<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> + +</pre> + +<pre class="brush: css"> +.box { + float: left; + width: 150px; + height: 150px; + margin-right: 30px; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('Float_1', '100%', 600) }}</p> + +<div class="note"> +<p><strong>Note</strong>: Floats are fully explained in our lesson on the <a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">float and clear</a> properties. Prior to techniques such as Flexbox and Grid Layout floats were used as a method of creating column layouts. You may still come across these methods on the web; we will cover these in the lesson on <a href="/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods">legacy layout methods</a>.</p> +</div> + +<h2 id="Positioning_techniques">Positioning techniques</h2> + +<p>Positioning allows you to move an element from where it would be placed when in normal flow to another location. Positioning isn’t a method for creating your main page layouts, it is more about managing and fine-tuning the position of specific items on the page.</p> + +<p>There are however useful techniques for certain layout patterns that rely on the {{cssxref("position")}} property. Understanding positioning also helps in understanding normal flow, and what it is to move an item out of normal flow.</p> + +<p>There are five types of positioning you should know about:</p> + +<ul> + <li><strong>Static positioning</strong> is the default that every element gets — it just means "put the element into its normal position in the document layout flow — nothing special to see here".</li> + <li><strong>Relative positioning</strong> allows you to modify an element's position on the page, moving it relative to its position in normal flow — including making it overlap other elements on the page.</li> + <li><strong>Absolute positioning</strong> moves an element completely out of the page's normal layout flow, like it is sitting on its own separate layer. From there, you can fix it in a position relative to the edges of the page's <code><html></code> element (or its nearest positioned ancestor element). This is useful for creating complex layout effects such as tabbed boxes where different content panels sit on top of one another and are shown and hidden as desired, or information panels that sit off screen by default, but can be made to slide on screen using a control button.</li> + <li><strong>Fixed positioning</strong> is very similar to absolute positioning, except that it fixes an element relative to the browser viewport, not another element. This is useful for creating effects such as a persistent navigation menu that always stays in the same place on the screen as the rest of the content scrolls.</li> + <li><strong>Sticky positioning</strong> is a newer positioning method which makes an element act like <code>position: static</code> until it hits a defined offset from the viewport, at which point it acts like <code>position: fixed</code>.</li> +</ul> + +<h3 id="Simple_positioning_example">Simple positioning example</h3> + +<p>To provide familiarity with these page layout techniques, we'll show you a couple of quick examples. Our examples will all feature the same HTML, which is as follows:</p> + +<pre class="brush: html"><h1>Positioning</h1> + +<p>I am a basic block level element.</p> +<p class="positioned">I am a basic block level element.</p> +<p>I am a basic block level element.</p></pre> + +<p>This HTML will be styled by default using the following CSS:</p> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; +} + +p { + background-color: rgb(207,232,220); + border: 2px solid rgb(79,185,227); + padding: 10px; + margin: 10px; + border-radius: 5px; +} +</pre> + +<p>The rendered output is as follows:</p> + +<p>{{ EmbedLiveSample('Simple_positioning_example', '100%', 300) }}</p> + +<h3 id="Relative_positioning">Relative positioning</h3> + +<p>Relative positioning allows you to offset an item from the position in normal flow it would have by default. This means you could achieve a task such as moving an icon down a bit so it lines up with a text label. To do this, we could add the following rule to add relative positioning:</p> + +<pre class="brush: css">.positioned { + position: relative; + top: 30px; + left: 30px; +}</pre> + +<p>Here we give our middle paragraph a {{cssxref("position")}} value of <code>relative</code> — this doesn't do anything on its own, so we also add {{cssxref("top")}} and {{cssxref("left")}} properties. These serve to move the affected element down and to the right — this might seem like the opposite of what you were expecting, but you need to think of it as the element being pushed on its left and top sides, which result in it moving right and down.</p> + +<p>Adding this code will give the following result:</p> + +<div id="Relative_1"> +<div class="hidden"> +<h6 id="Relative_positioning_example">Relative positioning example</h6> + +<pre class="brush: html"><h1>Relative positioning</h1> + +<p>I am a basic block level element.</p> +<p class="positioned">This is my relatively positioned element.</p> +<p>I am a basic block level element.</p></pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; +} + +p { + background-color: rgb(207,232,220); + border: 2px solid rgb(79,185,227); + padding: 10px; + margin: 10px; + border-radius: 5px; +} +</pre> +</div> + +<pre class="brush: css">.positioned { + position: relative; + background: rgba(255,84,104,.3); + border: 2px solid rgb(255,84,104); + top: 30px; + left: 30px; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Relative_1', '100%', 300) }}</p> + +<h3 id="Absolute_positioning">Absolute positioning</h3> + +<p>Absolute positioning is used to completely remove an element from normal flow, and place it using offsets from the edges of a containing block.</p> + +<p>Going back to our original non-positioned example, we could add the following CSS rule to implement absolute positioning:</p> + +<pre class="brush: css">.positioned { + position: absolute; + top: 30px; + left: 30px; +}</pre> + +<p>Here we give our middle paragraph a {{cssxref("position")}} value of <code>absolute</code>, and the same {{cssxref("top")}} and {{cssxref("left")}} properties as before. Adding this code, however, will give the following result:</p> + +<div id="Absolute_1"> +<div class="hidden"> +<h6 id="Absolute_positioning_example">Absolute positioning example</h6> + +<pre class="brush: html"><h1>Absolute positioning</h1> + +<p>I am a basic block level element.</p> +<p class="positioned">This is my absolutely positioned element.</p> +<p>I am a basic block level element.</p></pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; +} + +p { + background-color: rgb(207,232,220); + border: 2px solid rgb(79,185,227); + padding: 10px; + margin: 10px; + border-radius: 5px; +} +</pre> +</div> + +<pre class="brush: css">.positioned { + position: absolute; + background: rgba(255,84,104,.3); + border: 2px solid rgb(255,84,104); + top: 30px; + left: 30px; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Absolute_1', '100%', 300) }}</p> + +<p>This is very different! The positioned element has now been completely separated from the rest of the page layout and sits over the top of it. The other two paragraphs now sit together as if their positioned sibling doesn't exist. The {{cssxref("top")}} and {{cssxref("left")}} properties have a different effect on absolutely positioned elements than they do on relatively positioned elements. In this case the offsets have been calculated from the top and left of the page. It is possible to change the parent element that becomes this container and we will take a look at that in the lesson on <a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">positioning</a>.</p> + +<h3 id="Fixed_positioning">Fixed positioning</h3> + +<p>Fixed positioning removes our element from document flow in the same way as absolute positioning. However, instead of the offsets being applied from the container, they are applied from the viewport. As the item remains fixed in relation to the viewport we can create effects such as a menu which remains fixed as the page scrolls beneath it.</p> + +<p>For this example our HTML is three paragraphs of text, in order that we can cause the page to scroll, and a box to which we will give <code>position: fixed</code>.</p> + +<pre class="brush: html"><h1>Fixed positioning</h1> + +<div class="positioned">Fixed</div> + +<p>Paragraph 1.</p> +<p>Paragraph 2.</p> +<p>Paragraph 3.</p> +</pre> + +<div id="Fixed_1"> +<div class="hidden"> +<h6 id="Fixed_positioning_example">Fixed positioning example</h6> + +<pre class="brush: html"><h1>Fixed positioning</h1> + +<div class="positioned">Fixed</div> + +<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> + +<p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> + +<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> + +</pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; +} + +.positioned { + background: rgba(255,84,104,.3); + border: 2px solid rgb(255,84,104); + padding: 10px; + margin: 10px; + border-radius: 5px; +}</pre> +</div> + +<pre class="brush: css">.positioned { + position: fixed; + top: 30px; + left: 30px; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Fixed_1', '100%', 200) }}</p> + +<h3 id="Sticky_positioning">Sticky positioning</h3> + +<p>Sticky positioning is the final positioning method that we have at our disposal. It mixes the default static positioning with fixed positioning. When an item has <code>position: sticky</code> it will scroll in normal flow until it hits offsets from the viewport that we have defined. At that point it becomes "stuck" as if it had <code>position: fixed</code> applied.</p> + +<div id="Sticky_1"> +<div class="hidden"> +<h6 id="Sticky_positioning_example">Sticky positioning example</h6> + +<pre class="brush: html"><h1>Sticky positioning</h1> + +<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> + +<div class="positioned">Sticky</div> + +<p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> + +<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> </pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; +} + +.positioned { + background: rgba(255,84,104,.3); + border: 2px solid rgb(255,84,104); + padding: 10px; + margin: 10px; + border-radius: 5px; +}</pre> +</div> + +<pre class="brush: css">.positioned { + position: sticky; + top: 30px; + left: 30px; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Sticky_1', '100%', 200) }}</p> + +<div class="note"> +<p><strong>Note</strong>: to find more out about positioning, see our <a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">Positioning</a> article.</p> +</div> + +<h2 id="Table_layout">Table layout</h2> + +<p>HTML tables are fine for displaying tabular data, but many years ago — before even basic CSS was supported reliably across browsers — web developers used to also use tables for entire web page layouts — putting their headers, footers, different columns, etc. in various table rows and columns. This worked at the time, but it has many problems — table layouts are inflexible, very heavy on markup, difficult to debug, and semantically wrong (e.g., screen reader users have problems navigating table layouts).</p> + +<p>The way that a table looks on a webpage when you use table markup is due to a set of CSS properties that define table layout. These properties can be used to lay out elements that are not tables, a use which is sometimes described as "using CSS tables".</p> + +<p>The example below shows one such use; using CSS tables for layout should be considered a legacy method at this point, for those situations where you have very old browsers without support for Flexbox or Grid.</p> + +<p>Let's look at an example. First, some simple markup that creates an HTML form. Each input element has a label, and we've also included a caption inside a paragraph. Each label/input pair is wrapped in a {{htmlelement("div")}}, for layout purposes.</p> + +<pre class="brush: html"><form> + <p>First of all, tell us your name and age.</p> + <div> + <label for="fname">First name:</label> + <input type="text" id="fname"> + </div> + <div> + <label for="lname">Last name:</label> + <input type="text" id="lname"> + </div> + <div> + <label for="age">Age:</label> + <input type="text" id="age"> + </div> +</form></pre> + +<p>Now, the CSS for our example. Most of the CSS is fairly ordinary, except for the uses of the {{cssxref("display")}} property. The {{htmlelement("form")}}, {{htmlelement("div")}}s, and {{htmlelement("label")}}s and {{htmlelement("input")}}s have been told to display like a table, table rows, and table cells respectively — basically, they'll act like HTML table markup, causing the labels and inputs to line up nicely by default. All we then have to do is add a bit of sizing, margin, etc. to make everything look a bit nicer and we're done.</p> + +<p>You'll notice that the caption paragraph has been given <code>display: table-caption;</code> — which makes it act like a table {{htmlelement("caption")}} — and <code>caption-side: bottom;</code> to tell the caption to sit on the bottom of the table for styling purposes, even though the markup is before the <code><input></code> elements in the source. This allows for a nice bit of flexibility.</p> + +<pre class="brush: css">html { + font-family: sans-serif; +} + +form { + display: table; + margin: 0 auto; +} + +form div { + display: table-row; +} + +form label, form input { + display: table-cell; + margin-bottom: 10px; +} + +form label { + width: 200px; + padding-right: 5%; + text-align: right; +} + +form input { + width: 300px; +} + +form p { + display: table-caption; + caption-side: bottom; + width: 300px; + color: #999; + font-style: italic; +}</pre> + +<p>This gives us the following result:</p> + +<p>{{ EmbedLiveSample('Table_layout', '100%', '170') }}</p> + +<p>You can also see this example live at <a href="https://mdn.github.io/learning-area/css/styling-boxes/box-model-recap/css-tables-example.html">css-tables-example.html</a> (see the <a href="https://github.com/mdn/learning-area/blob/master/css/styling-boxes/box-model-recap/css-tables-example.html">source code</a> too.)</p> + +<h2 id="Multi-column_layout">Multi-column layout</h2> + +<p>The multi-column layout module gives us a way to lay out content in columns, similar to how text flows in a newspaper. While reading up and down columns is less useful in a web context as you don’t want to force users to scroll up and down, arranging content into columns can be a useful technique.</p> + +<p>To turn a block into a multicol container we use either the {{cssxref("column-count")}} property, which tells the browser how many columns we would like to have, or the {{cssxref("column-width")}} property, which tells the browser to fill the container with as many columns of at least that width.</p> + +<p>In the below example we start with a block of HTML inside a containing <code><div></code> element with a class of <code>container</code>.</p> + +<pre class="brush: html"><div class="container"> + <h1>Multi-column layout</h1> + + <p>Paragraph 1.</p> + <p>Paragraph 2.</p> + +</div> +</pre> + +<p>We are using a <code>column-width</code> of 200 pixels on that container, causing the browser to create as many 200-pixel columns as will fit in the container and then share the remaining space between the created columns.</p> + +<div id="Multicol_1"> +<div class="hidden"> +<h6 id="Multicol_example">Multicol example</h6> + +<pre class="brush: html"> <div class="container"> + <h1>Multi-column Layout</h1> + + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> + + + <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> + + </div> + </pre> + +<pre class="brush: css">body { max-width: 800px; margin: 0 auto; } </pre> +</div> + +<pre class="brush: css"> .container { + column-width: 200px; + }</pre> +</div> + +<p>{{ EmbedLiveSample('Multicol_1', '100%', 200) }}</p> + +<h2 id="Summary">Summary</h2> + +<p>This article has provided a brief summary of all the layout technologies you should know about. Read on for more information on each individual technology!</p> + +<p>{{NextMenu("Learn/CSS/CSS_layout/Normal_Flow", "Learn/CSS/CSS_layout")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Introduction">Introduction to CSS layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Normal_Flow">Normal flow</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grid</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">Floats</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">Positioning</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout">Multiple-column layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design">Responsive design</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Media_queries">Beginner's guide to media queries</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods">Legacy layout methods</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Supporting_Older_Browsers">Supporting older browsers</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension">Fundamental layout comprehension assessment</a></li> +</ul> diff --git a/files/pt-br/learn/css/css_layout/layout_de_varias_colunas/index.html b/files/pt-br/learn/css/css_layout/layout_de_varias_colunas/index.html new file mode 100644 index 0000000000..2605843ff4 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/layout_de_varias_colunas/index.html @@ -0,0 +1,414 @@ +--- +title: Layout de varias colunas +slug: Learn/CSS/CSS_layout/Layout_de_varias_colunas +translation_of: Learn/CSS/CSS_layout/Multiple-column_Layout +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/CSS/CSS_layout/Positioning", "Learn/CSS/CSS_layout/Responsive_Design", "Learn/CSS/CSS_layout")}}</div> + +<p class="summary">A especificação de layout de várias colunas fornece um método de disposição do conteúdo em colunas, como você pode ver em um jornal. Este artigo explica como usar esse recurso.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Pré requisitos:</th> + <td>HTML basico (estude <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Introduction to HTML</a>) e uma ideia de como CSS funciona (estude <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introduction to CSS</a>).</td> + </tr> + <tr> + <th scope="row">Objetivo:</th> + <td> + <p>Aprender como criar layouts de várias colunas em paginas web, tal qual estão formatadas as paginas de um jornal.</p> + + + </td> + </tr> + </tbody> +</table> + +<h2 id="Um_exemplo_basico">Um exemplo basico</h2> + +<p>Agora nós vamos explorar como usar layouts de varias colunas, frequentemente referido como <em>multicol</em>. Você pode começar pelo <a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/multicol/0-starting-point.html">download do arquivo multicol - ponto de partida</a>, e adicionar o CSS nos locais apropriados. Na parte inferior desta seção, você pode ver um exemplo real da aparência do código final.</p> + +<p>Nosso ponto de partida contem um HTML simples; um invólucro com uma classe de <code>container</code> dentro do qual há um cabeçalho e alguns parágrafos.</p> + +<p>O {{htmlelement("div")}} com a classe de container se tornará nosso <em>muticol</em> container. Nós ativamos o <em>multicol</em> usando uma de duas propriedades {{cssxref("column-count")}} ou {{cssxref("column-width")}}. A propriedade <code>column-count</code> criará tantas colunas quanto o valor que você atribuir; portanto, se voce adicionar o seguinte CSS à sua <em>stylesheet</em> e recarregar a pagina, você obterá três colunas:</p> + +<p> + </p><pre class="brush: css">.container { + column-count: 3; +} +</pre> + + +<p>As colunas que você criar têm larguras flexíveis - o navegador calcula quanto espaço será atribuido a cada coluna.</p> + +<div id="Multicol_1"> +<div class="hidden"> +<h6 id="column-count_example">column-count example</h6> + +<pre class="brush: css">body { + width: 90%; + max-width: 900px; + margin: 2em auto; + font: .9em/1.2 Arial, Helvetica, sans-serif; +} + </pre> +</div> + +<pre class="brush: html"><div class="container"> + <h1>Simple multicol example</h1> + + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. + Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. + Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse + ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit + quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> + + <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique + elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit + cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis + dis parturient montes, nascetur ridiculus mus.</p> +</div> +</pre> + +<pre class="brush: css">.container { + column-count: 3; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('Multicol_1', '100%', 400) }}</p> + +<p>Mude o seu CSS para usar <code>column-width</code>, como a seguir:</p> + +<pre class="brush: css">.container { + column-width: 200px; +} +</pre> + +<p>O navegador agora fornecerá o maior número possível de colunas, do tamanho que você especificar; qualquer espaço restante é compartilhado entre as colunas existentes. Isso significa que você não terá exatamente a largura que especificar, a menos que seu container seja exatamente divisível por essa largura.</p> + +<div id="Multicol_2"> +<div class="hidden"> +<h6 id="column-width_example">column-width example</h6> + +<pre class="brush: css">body { + width: 90%; + max-width: 900px; + margin: 2em auto; + font: .9em/1.2 Arial, Helvetica, sans-serif; +}</pre> + +<pre class="brush: html"><div class="container"> + <h1>Simple multicol example</h1> + + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. + Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. + Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse + ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit + quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> + + <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique + elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit + cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis + dis parturient montes, nascetur ridiculus mus.</p> +</div></pre> +</div> + +<pre class="brush: css">.container { + column-width: 200px; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('Multicol_2', '100%', 400) }}</p> + +<h2 id="Styling_the_columns">Styling the columns</h2> + +<p>The columns created by multicol cannot be styled individually. There is no way to make one column bigger than other columns, or to change the background or text color of a single column. You have two opportunities to change the way that columns display:</p> + +<ul> + <li>Changing the size of the gap between columns using the {{cssxref("column-gap")}}.</li> + <li>Adding a rule between columns with {{cssxref("column-rule")}}.</li> +</ul> + +<p>Using your example above, change the size of the gap by adding a <code>column-gap</code> property:</p> + +<pre class="brush: css">.container { + column-width: 200px; + column-gap: 20px; +}</pre> + +<p>You can play around with different values — the property accepts any length unit. Now add a rule between the columns, with <code>column-rule</code>. In a similar way to the {{cssxref("border")}} property that you encountered in previous lessons, <code>column-rule</code> is a shorthand for {{cssxref("column-rule-color")}}, {{cssxref("column-rule-style")}}, and {{cssxref("column-rule-width")}}, and accepts the same values as <code>border</code>.</p> + +<pre class="brush: css">.container { + column-count: 3; + column-gap: 20px; + column-rule: 4px dotted rgb(79, 185, 227); +}</pre> + +<p>Try adding rules of different styles and colors.</p> + +<div id="Multicol_3"> +<div class="hidden"> +<h6 id="Styling_the_columns_2">Styling the columns</h6> + +<pre class="brush: css">body { + width: 90%; + max-width: 900px; + margin: 2em auto; + font: .9em/1.2 Arial, Helvetica, sans-serif; +} +.container { + column-count: 3; + column-gap: 20px; + column-rule: 4px dotted rgb(79, 185, 227); +}</pre> + +<pre class="brush: html"><div class="container"> + <h1>Simple multicol example</h1> + + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. + Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. + Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse + ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit + quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> + + <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique + elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit + cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis + dis parturient montes, nascetur ridiculus mus.</p> +</div></pre> +</div> +</div> + +<p>{{ EmbedLiveSample('Multicol_3', '100%', 400) }}</p> + +<p>Something to take note of is that the rule does not take up any width of its own. It lies across the gap you created with <code>column-gap</code>. To make more space either side of the rule you will need to increase the <code>column-gap</code> size.</p> + +<h2 id="Columns_and_fragmentation">Columns and fragmentation</h2> + +<p>The content of a multi-column layout is fragmented. It essentially behaves the same way as content behaves in paged media — such as when you print a webpage. When you turn your content into a multicol container it is fragmented into columns, and the content breaks to allow this to happen.</p> + +<p>Sometimes, this breaking will happen in places that lead to a poor reading experience. In the live example below, I have used multicol to lay out a series of boxes, each of which have a heading and some text inside. The heading becomes separated from the text if the columns fragment between the two.</p> + +<div id="Multicol_4"> +<div class="hidden"> +<h6 id="Cards_example">Cards example</h6> + +<pre class="brush: css">body { + width: 90%; + max-width: 900px; + margin: 2em auto; + font: .9em/1.2 Arial, Helvetica, sans-serif; +} </pre> +</div> + +<pre class="brush: html"><div class="container"> + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + +</div> +</pre> + +<pre class="brush: css">.container { + column-width: 250px; + column-gap: 20px; +} + +.card { + background-color: rgb(207, 232, 220); + border: 2px solid rgb(79, 185, 227); + padding: 10px; + margin: 0 0 1em 0; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Multicol_4', '100%', 600) }}</p> + +<p>To control this behavior we can use properties from the <a href="/en-US/docs/Web/CSS/CSS_Fragmentation">CSS Fragmentation</a> specification. This specification gives us properties to control breaking of content in multicol and in paged media. For example, add the property {{cssxref("break-inside")}} with a value of <code>avoid</code> to the rules for <code>.card</code>. This is the container of the heading and text, and therefore we do not want to fragment this box.</p> + +<p>At the present time it is also worth adding the older property <code>page-break-inside: avoid</code> for best browser support.</p> + +<pre class="brush: css">.card { + break-inside: avoid; + page-break-inside: avoid; + background-color: rgb(207,232,220); + border: 2px solid rgb(79,185,227); + padding: 10px; + margin: 0 0 1em 0; +} +</pre> + +<p>Reload the page and your boxes should stay in one piece.</p> + +<div id="Multicol_5"> +<div class="hidden"> +<h6 id="Multicol_Fragmentation">Multicol Fragmentation</h6> + +<pre class="brush: css">body { + width: 90%; + max-width: 900px; + margin: 2em auto; + font: .9em/1.2 Arial, Helvetica, sans-serif; +} </pre> + +<pre class="brush: html"><div class="container"> + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + + <div class="card"> + <h2>I am the heading</h2> + <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat + vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies + tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci + vel, viverra egestas ligula.</p> + </div> + +</div> +</pre> +</div> + +<pre class="brush: css">.container { + column-width: 250px; + column-gap: 20px; +} + +.card { + break-inside: avoid; + page-break-inside: avoid; + background-color: rgb(207, 232, 220); + border: 2px solid rgb(79, 185, 227); + padding: 10px; + margin: 0 0 1em 0; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Multicol_5', '100%', 600) }}</p> + +<h2 id="Summary">Summary</h2> + +<p>You now know how to use the basic features of multiple-column layout, another tool at your disposal when choosing a layout method for the designs you are building.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Fragmentation">CSS Fragmentation</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Columns/Using_multi-column_layouts">Using multi-column layouts</a></li> +</ul> + +<p>{{PreviousMenuNext("Learn/CSS/CSS_layout/Positioning", "Learn/CSS/CSS_layout/Responsive_Design", "Learn/CSS/CSS_layout")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Introduction">Introduction to CSS layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Normal_Flow">Normal flow</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grid</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">Floats</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">Positioning</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout">Multiple-column layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design">Responsive design</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Media_queries">Beginner's guide to media queries</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods">Legacy layout methods</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Supporting_Older_Browsers">Supporting older browsers</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension">Fundamental layout comprehension assessment</a></li> +</ul> diff --git a/files/pt-br/learn/css/css_layout/positioning/index.html b/files/pt-br/learn/css/css_layout/positioning/index.html new file mode 100644 index 0000000000..51a024e875 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/positioning/index.html @@ -0,0 +1,574 @@ +--- +title: Positioning +slug: Learn/CSS/CSS_layout/Positioning +translation_of: Learn/CSS/CSS_layout/Positioning +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Aprenda/CSS/CSS_layout/Floats", "Aprenda/CSS/CSS_layout/Multiple-column_Layout", "Aprenda/CSS/CSS_layout")}}</div> + +<p class="summary">Positioning allows you to take elements out of the normal document layout flow, and make them behave differently; for example sitting on top of one another, or always remaining in the same place inside the browser viewport. This article explains the different {{cssxref("position")}} values, and how to use them.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Prerequisites:</th> + <td>HTML basics (study <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Introduction to HTML</a>), and an idea of How CSS works (study <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introduction to CSS</a>.)</td> + </tr> + <tr> + <th scope="row">Objective:</th> + <td>To learn how CSS positioning works.</td> + </tr> + </tbody> +</table> + +<p>We'd like you to follow along with the exercises on your local computer, if possible — grab a copy of <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/0_basic-flow.html">0_basic-flow.html</a></code> from our GitHub repo (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/0_basic-flow.html">source code here</a>) and use that as a starting point.</p> + +<h2 id="Introducing_positioning">Introducing positioning</h2> + +<p>The whole idea of positioning is to allow us to override the basic document flow behavior described above, to produce interesting effects. What if you want to slightly alter the position of some boxes inside a layout from their default layout flow position, to give a slightly quirky, distressed feel? Positioning is your tool. Or if you want to create a UI element that floats over the top of other parts of the page, and/or always sits in the same place inside the browser window no matter how much the page is scrolled? Positioning makes such layout work possible.</p> + +<p>There are a number of different types of positioning that you can put into effect on HTML elements. To make a specific type of positioning active on an element, we use the {{cssxref("position")}} property.</p> + +<h3 id="Static_positioning">Static positioning</h3> + +<p>Static positioning is the default that every element gets — it just means "put the element into its normal position in the document layout flow — nothing special to see here."</p> + +<p>To demonstrate this, and get your example set up for future sections, first add a <code>class</code> of <code>positioned</code> to the second {{htmlelement("p")}} in the HTML:</p> + +<pre class="brush: html"><p class="positioned"> ... </p></pre> + +<p>Now add the following rule to the bottom of your CSS:</p> + +<pre class="brush: css">.positioned { + position: static; + background: yellow; +}</pre> + +<p>If you now save and refresh, you'll see no difference at all, except for the updated background color of the 2nd paragraph. This is fine — as we said before, static positioning is the default behavior!</p> + +<div class="note"> +<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/1_static-positioning.html">1_static-positioning.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/1_static-positioning.html">see source code</a>).</p> +</div> + +<h3 id="Relative_positioning">Relative positioning</h3> + +<p>Relative positioning is the first position type we'll take a look at. This is very similar to static positioning, except that once the positioned element has taken its place in the normal layout flow, you can then modify its final position, including making it overlap other elements on the page. Go ahead and update the <code>position</code> declaration in your code:</p> + +<pre class="brush: css">position: relative;</pre> + +<p>If you save and refresh at this stage, you won't see a change in the result at all. So how do you modify the element's position? You need to use the {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} properties, which we'll explain in the next section.</p> + +<h3 id="Introducing_top_bottom_left_and_right">Introducing top, bottom, left, and right</h3> + +<p>{{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} are used alongside {{cssxref("position")}} to specify exactly where to move the positioned element to. To try this out, add the following declarations to the <code>.positioned</code> rule in your CSS:</p> + +<pre class="brush: css">top: 30px; +left: 30px;</pre> + +<div class="note"> +<p><strong>Note</strong>: The values of these properties can take any <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Values_and_units">units</a> you'd logically expect — pixels, mm, rems, %, etc.</p> +</div> + +<p>If you now save and refresh, you'll get a result something like this:</p> + +<div class="hidden"> +<pre class="brush: html"><h1>Relative positioning</h1> + +<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> + +<p class="positioned">By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p> + +<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> + +<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; +} + +p { + background: aqua; + border: 3px solid blue; + padding: 10px; + margin: 10px; +} + +span { + background: red; + border: 1px solid black; +} + +.positioned { + position: relative; + background: yellow; + top: 30px; + left: 30px; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Introducing_top_bottom_left_and_right', '100%', 500) }}</p> + +<p>Cool, huh? Ok, so this probably wasn't what you were expecting — why has it moved to the bottom and right if we specified top and left? Illogical as it may initially sound, this is just the way that relative positioning works — you need to think of an invisible force that pushes the specified side of the positioned box, moving it in the opposite direction. So for example, if you specify <code>top: 30px;</code>, a force pushes the top of the box, causing it to move downwards by 30px.</p> + +<div class="note"> +<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/2_relative-positioning.html">2_relative-positioning.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/2_relative-positioning.html">see source code</a>).</p> +</div> + +<h3 id="Absolute_positioning">Absolute positioning</h3> + +<p>Absolute positioning brings very different results. Let's try changing the position declaration in your code as follows:</p> + +<pre class="brush: css">position: absolute;</pre> + +<p>If you now save and refresh, you should see something like so:</p> + +<div class="hidden"> +<pre class="brush: html"><h1>Absolute positioning</h1> + +<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> + +<p class="positioned">By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p> + +<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> + +<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; +} + +p { + background: aqua; + border: 3px solid blue; + padding: 10px; + margin: 10px; +} + +span { + background: red; + border: 1px solid black; +} + +.positioned { + position: absolute; + background: yellow; + top: 30px; + left: 30px; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Absolute_positioning', '100%', 420) }}</p> + +<p>First of all, note that the gap where the positioned element should be in the document flow is no longer there — the first and third elements have closed together like it no longer exists! Well, in a way, this is true. An absolutely positioned element no longer exists in the normal document layout flow. Instead, it sits on its own layer separate from everything else. This is very useful: it means that we can create isolated UI features that don't interfere with the position of other elements on the page. For example, popup information boxes and control menus; rollover panels; UI features that can be dragged and dropped anywhere on the page; and so on...</p> + +<p>Second, notice that the position of the element has changed — this is because {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} behave in a different way with absolute positioning. Instead of specifying the direction the element should move in, they specify the distance the element should be from each containing element's sides. So in this case, we are saying that the absolutely positioned element should sit 30px from the top of the "containing element", and 30px from the left.</p> + +<div class="note"> +<p><strong>Note</strong>: You can use {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} to resize elements if you need to. Try setting <code>top: 0; bottom: 0; left: 0; right: 0;</code> and <code>margin: 0;</code> on your positioned elements and see what happens! Put it back again afterwards...</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: Yes, margins still affect positioned elements. Margin collapsing doesn't, however.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/3_absolute-positioning.html">3_absolute-positioning.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/3_absolute-positioning.html">see source code</a>).</p> +</div> + +<h3 id="Positioning_contexts">Positioning contexts</h3> + +<p>Which element is the "containing element" of an absolutely positioned element? This is very much dependent on the position property of the ancestors of the positioned element (See <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#Identifying_the_containing_block">Identifying the containing block</a>). </p> + +<p>If no ancestor elements have their position property explicitly defined, then by default all ancestor elements will have a static position. The result of this is, the absolutely positioned element will be contained in the <strong>initial containing block</strong>. The initial containing block has the dimensions of the viewport, and is also the block that contains the {{htmlelement("html")}} element. Simply put, the absolutely positioned element will be contained outside of the {{htmlelement("html")}} element, and be positioned relative to the initial viewport. </p> + +<p>The positioned element is nested inside the {{htmlelement("body")}} in the HTML source, but in the final layout, it is 30px away from the top and left of the edge of the page. We can change the <strong>positioning context</strong> — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors — to one of the elements it is nested inside (you can't position it relative to an element it is not nested inside). To demonstrate this, add the following declaration to your <code>body</code> rule:</p> + +<pre class="brush: css">position: relative;</pre> + +<p>This should give the following result:</p> + +<div class="hidden"> +<pre class="brush: html"><h1>Positioning context</h1> + +<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> + +<p class="positioned">Now I'm absolutely positioned relative to the <code>&lt;body&gt;</code> element, not the <code>&lt;html&gt;</code> element!</p> + +<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> + +<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; + position: relative; +} + +p { + background: aqua; + border: 3px solid blue; + padding: 10px; + margin: 10px; +} + +span { + background: red; + border: 1px solid black; +} + +.positioned { + position: absolute; + background: yellow; + top: 30px; + left: 30px; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Positioning_contexts', '100%', 420) }}</p> + +<p>The positioned element now sits relative to the {{htmlelement("body")}} element.</p> + +<div class="note"> +<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/4_positioning-context.html">4_positioning-context.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/4_positioning-context.html">see source code</a>).</p> +</div> + +<h3 id="Introducing_z-index">Introducing z-index</h3> + +<p>All this absolute positioning is good fun, but there is another thing we haven't considered yet — when elements start to overlap, what determines which elements appear on top of which other elements? In the example we've seen so far, we only have one positioned element in the positioning context, and it appears on the top, since positioned elements win over non-positioned elements. What about when we have more than one?</p> + +<p>Try adding the following to your CSS, to make the first paragraph absolutely positioned too:</p> + +<pre class="brush: css">p:nth-of-type(1) { + position: absolute; + background: lime; + top: 10px; + right: 30px; +}</pre> + +<p>At this point you'll see the first paragraph colored lime, moved out of the document flow, and positioned a bit above from where it originally was. It is also stacked below the original <code>.positioned</code> paragraph, where the two overlap. This is because the <code>.positioned</code> paragraph is the second paragraph in the source order, and positioned elements later in the source order win over positioned elements earlier in the source order.</p> + +<p>Can you change the stacking order? Yes, you can, by using the {{cssxref("z-index")}} property. "z-index" is a reference to the z-axis. You may recall from previous points in the course where we discussed web pages using horizontal (x-axis) and vertical (y-axis) coordinates to work out positioning for things like background images and drop shadow offsets. (0,0) is at the top left of the page (or element), and the x- and y-axes run across to the right and down the page (for left to right languages, anyway.)</p> + +<p>Web pages also have a z-axis: an imaginary line that runs from the surface of your screen, towards your face (or whatever else you like to have in front of the screen). {{cssxref("z-index")}} values affect where positioned elements sit on that axis; positive values move them higher up the stack, and negative values move them lower down the stack. By default, positioned elements all have a <code>z-index</code> of <code>auto</code>, which is effectively 0.</p> + +<p>To change the stacking order, try adding the following declaration to your <code>p:nth-of-type(1)</code> rule:</p> + +<pre class="brush: css">z-index: 1;</pre> + +<p>You should now see the finished example, with the lime paragraph on top:</p> + +<div class="hidden"> +<pre class="brush: html"><h1>z-index</h1> + +<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> + +<p class="positioned">Now I'm absolutely positioned relative to the <code>&lt;body&gt;</code> element, not the <code>&lt;html&gt;</code> element!</p> + +<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> + +<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; + position: relative; +} + +p { + background: aqua; + border: 3px solid blue; + padding: 10px; + margin: 10px; +} + +span { + background: red; + border: 1px solid black; +} + +.positioned { + position: absolute; + background: yellow; + top: 30px; + left: 30px; +} + +p:nth-of-type(1) { + position: absolute; + background: lime; + top: 10px; + right: 30px; + z-index: 1; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('Introducing_z-index', '100%', 400) }}</p> + +<p>Note that <code>z-index</code> only accepts unitless index values; you can't specify that you want one element to be 23 pixels up the Z-axis — it doesn't work like that. Higher values will go above lower values, and it is up to you what values you use. Using 2 and 3 would give the same effect as 300 and 40000.</p> + +<div class="note"> +<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/5_z-index.html">5_z-index.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/5_z-index.html">see source code</a>).</p> +</div> + +<h3 id="Fixed_positioning">Fixed positioning</h3> + +<p>Let's now look at fixed positioning. This works in exactly the same way as absolute positioning, with one key difference: whereas absolute positioning fixes an element in place relative to the {{htmlelement("html")}} element or its nearest positioned ancestor, fixed positioning fixes an element in place relative to the browser viewport itself. This means that you can create useful UI items that are fixed in place, like persisting navigation menus.</p> + +<p>Let's put together a simple example to show what we mean. First of all, delete the existing <code>p:nth-of-type(1)</code> and <code>.positioned</code> rules from your CSS.</p> + +<p>Now, update the <code>body</code> rule to remove the <code>position: relative;</code> declaration and add a fixed height, like so:</p> + +<pre class="brush: css">body { + width: 500px; + height: 1400px; + margin: 0 auto; +}</pre> + +<p>Now we're going to give the {{htmlelement("h1")}} element <code>position: fixed;</code>, and get it to sit at the top center of the viewport. Add the following rule to your CSS:</p> + +<pre class="brush: css">h1 { + position: fixed; + top: 0; + width: 500px; + margin: 0 auto; + background: white; + padding: 10px; +}</pre> + +<p>The <code>top: 0;</code> is required to make it stick to the top of the screen; we then give the heading the same width as the content column and use the faithful old <code>margin: 0 auto;</code> trick to center it. We then give it a white background and some padding, so the content won't be visible underneath it.</p> + +<p>If you save and refresh now, you'll see a fun little effect whereby the heading stays fixed, and the content appears to scroll up and disappear underneath it. But we could improve this more — at the moment some of the content starts off underneath the heading. This is because the positioned heading no longer appears in the document flow, so the rest of the content moves up to the top. We need to move it all down a bit; we can do this by setting some top margin on the first paragraph. Add this now:</p> + +<pre class="brush: css">p:nth-of-type(1) { + margin-top: 60px; +}</pre> + +<p>You should now see the finished example:</p> + +<div class="hidden"> +<pre class="brush: html"><h1>Fixed positioning</h1> + +<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> + +<p class="positioned">I'm not positioned any more...</p> + +<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> + +<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> + +<pre class="brush: css">body { + width: 500px; + height: 1400px; + margin: 0 auto; +} + +p { + background: aqua; + border: 3px solid blue; + padding: 10px; + margin: 10px; +} + +span { + background: red; + border: 1px solid black; +} + +h1 { + position: fixed; + top: 0px; + width: 500px; + margin: 0 auto; + background: white; + padding: 10px; +} + +p:nth-of-type(1) { + margin-top: 60px; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Fixed_positioning', '100%', 400) }}</p> + +<div class="note"> +<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/6_fixed-positioning.html">6_fixed-positioning.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/6_fixed-positioning.html">see source code</a>).</p> +</div> + +<h3 id="position_sticky">position: sticky</h3> + +<p>There is another position value available called <code>position: sticky</code>, which is somewhat newer than the others. This is basically a hybrid between relative and fixed position, which allows a positioned element to act like it is relatively positioned until it is scrolled to a certain threshold point (e.g. 10px from the top of the viewport), after which it becomes fixed. This can be used to for example cause a navigation bar to scroll with the page until a certain point, and then stick to the top of the page. </p> + +<div id="Sticky_1"> +<div class="hidden"> +<h6 id="Sticky_positioning_example">Sticky positioning example</h6> + +<pre class="brush: html"><h1>Sticky positioning</h1> + +<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> + +<div class="positioned">Sticky</div> + +<p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> + +<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> </pre> + +<pre class="brush: css">body { + width: 500px; + margin: 0 auto; +} + +.positioned { + background: rgba(255,84,104,.3); + border: 2px solid rgb(255,84,104); + padding: 10px; + margin: 10px; + border-radius: 5px; +}</pre> +</div> + +<pre class="brush: css">.positioned { + position: sticky; + top: 30px; + left: 30px; +}</pre> +</div> + +<p>{{ EmbedLiveSample('Sticky_1', '100%', 200) }}</p> + +<p>An interesting and common use of <code>position: sticky</code> is to create a scrolling index page where different headings stick to the top of the page as they reach it. The markup for such an example might look like so:</p> + +<pre class="brush: html"><h1>Sticky positioning</h1> + +<dl> + <dt>A</dt> + <dd>Apple</dd> + <dd>Ant</dd> + <dd>Altimeter</dd> + <dd>Airplane</dd> + <dt>B</dt> + <dd>Bird</dd> + <dd>Buzzard</dd> + <dd>Bee</dd> + <dd>Banana</dd> + <dd>Beanstalk</dd> + <dt>C</dt> + <dd>Calculator</dd> + <dd>Cane</dd> + <dd>Camera</dd> + <dd>Camel</dd> + <dt>D</dt> + <dd>Duck</dd> + <dd>Dime</dd> + <dd>Dipstick</dd> + <dd>Drone</dd> + <dt>E</dt> + <dd>Egg</dd> + <dd>Elephant</dd> + <dd>Egret</dd> +</dl> +</pre> + +<p>The CSS might look as follows. In normal flow the {{htmlelement("dt")}} elements will scroll with the content. When we add <code>position: sticky</code> to the {{htmlelement("dt")}} element, along with a {{cssxref("top")}} value of 0, supporting browsers will stick the headings to the top of the viewport as they reach that position. Each subsequent header will then replace the previous one as it scrolls up to that position.</p> + +<pre class="brush: css">dt { + background-color: black; + color: white; + padding: 10px; + position: sticky; + top: 0; + left: 0; + margin: 1em 0; +} +</pre> + +<div id="Sticky_2"> +<div class="hidden"> +<pre class="brush: css">body { + width: 500px; + height: 1400px; + margin: 0 auto; +} + +dt { + background-color: black; + color: white; + padding: 10px; + position: sticky; + top: 0; + left: 0; + margin: 1em 0; +} +</pre> + +<pre class="brush: html"><h1>Sticky positioning</h1> + +<dl> + <dt>A</dt> + <dd>Apple</dd> + <dd>Ant</dd> + <dd>Altimeter</dd> + <dd>Airplane</dd> + <dt>B</dt> + <dd>Bird</dd> + <dd>Buzzard</dd> + <dd>Bee</dd> + <dd>Banana</dd> + <dd>Beanstalk</dd> + <dt>C</dt> + <dd>Calculator</dd> + <dd>Cane</dd> + <dd>Camera</dd> + <dd>Camel</dd> + <dt>D</dt> + <dd>Duck</dd> + <dd>Dime</dd> + <dd>Dipstick</dd> + <dd>Drone</dd> + <dt>E</dt> + <dd>Egg</dd> + <dd>Elephant</dd> + <dd>Egret</dd> +</dl> +</pre> +</div> +</div> + +<p>{{ EmbedLiveSample('Sticky_2', '100%', 200) }}</p> + +<div class="note"> +<p><strong>Note</strong>: You can see this example live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/7_sticky-positioning.html">7_sticky-positioning.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/7_sticky-positioning.html">see source code</a>).</p> +</div> + +<h2 id="Summary">Summary</h2> + +<p>I'm sure you had fun playing with basic positioning; while it is not a method you would use for entire layouts, as you can see there are many tasks it is suited for.</p> + +<p>{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{cssxref("position")}} property reference.</li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Practical_positioning_examples">Practical positioning examples</a>, for some more useful ideas.</li> +</ul> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Introduction">Introduction to CSS layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Normal_Flow">Normal flow</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grid</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">Floats</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">Positioning</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout">Multiple-column layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design">Responsive design</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Media_queries">Beginner's guide to media queries</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods">Legacy layout methods</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Supporting_Older_Browsers">Supporting older browsers</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension">Fundamental layout comprehension assessment</a></li> +</ul> diff --git a/files/pt-br/learn/css/css_layout/responsive_design/index.html b/files/pt-br/learn/css/css_layout/responsive_design/index.html new file mode 100644 index 0000000000..bc554e4537 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/responsive_design/index.html @@ -0,0 +1,324 @@ +--- +title: Design Responsivo +slug: Learn/CSS/CSS_layout/Responsive_Design +translation_of: Learn/CSS/CSS_layout/Responsive_Design +--- +<div>{{learnsidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout/Media_queries", "Learn/CSS/CSS_layout")}}</div> + +<p>Nos primórdios do web design, páginas eram criadas para serem visualizadas em um tamanho de tela específico. Se o usuário tivesse uma tela maior ou menor do que o esperado, os resultados iam de barras de rolagem indesejadas, tamanhos de linha excessivamente longos e uso inadequado do espaço. À medida que diferentes tamanhos de tela foram aparecendo, surgiu o conceito de web design responsivo (RWD), um conjunto de práticas que permite que páginas da Web alterem seu layout e aparência para se adequarem a diferentes larguras, resoluções, etc. É uma ideia que mudou a forma de como projetamos para a Web com múltiplos dispositivos e, neste artigo, ajudaremos você a entender as principais técnicas que você precisa conhecer para dominá-la.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Prerrequisitos:</th> + <td>HTML básico (estude <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Introduction to HTML</a>), e uma idea de como o CSS funciona (estude <a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a> e <a href="/en-US/docs/Learn/CSS/Building_blocks">CSS building blocks</a>.)</td> + </tr> + <tr> + <th scope="row">Objetivo:</th> + <td>Entender os conceitos fundamentais e a história do design responsivo.</td> + </tr> + </tbody> +</table> + +<h2 id="História_dos_layouts_de_sites">História dos layouts de sites</h2> + +<p>Em algum ponto da história, você tinha duas opções ao criar um site:</p> + +<ul> + <li>Você pode criar um site <em>líquido</em>, que se estenderia para preencher a janela do navegador</li> + <li>ou um site de <em>largura fixa</em>, que seria um tamanho fixo em pixels.</li> +</ul> + +<p>Essas duas abordagens, geralmente, resultavam em um site com a melhor aparência na tela da pessoa que o projetava! O site líquido resultou em um design esmagado para telas menores (como visto abaixo) e comprimentos de linha muito longos em telas maiores.</p> + +<figure><img alt="A layout with two columns squashed into a mobile size viewport." src="https://mdn.mozillademos.org/files/16834/mdn-rwd-liquid.png" style="display: block; height: 406px; width: 300px;"> +<figcaption></figcaption> +</figure> + +<div class="blockIndicator note"> +<p><strong>Nota</strong>: Veja este layout líquido simples: <a href="https://mdn.github.io/css-examples/learn/rwd/liquid-width.html">exemplo</a>, <a href="https://github.com/mdn/css-examples/blob/master/learn/rwd/liquid-width.html">código-fonte</a>. Ao visualizar o exemplo, arraste a janela do navegador para dentro e para fora para ver como isso fica em tamanhos diferentes.</p> +</div> + +<p>O site de largura fixa criava uma barra de rolagem horizontal em telas menores que a largura do site (como mostrado abaixo) e muito espaço em branco nas bordas do design em telas maiores.</p> + +<figure><img alt="A layout with a horizontal scrollbar in a mobile viewport." src="https://mdn.mozillademos.org/files/16835/mdn-rwd-fixed.png" style="display: block; height: 411px; width: 300px;"> +<figcaption></figcaption> +</figure> + +<div class="blockIndicator note"> +<p><strong>Nota</strong>: Veja este layout simples de largura fixa: <a href="https://mdn.github.io/css-examples/learn/rwd/fixed-width.html">exemplo</a>, <a href="https://github.com/mdn/css-examples/blob/master/learn/rwd/fixed-width.html">código-fonte</a>. Observe novamente o resultado ao alterar o tamanho da janela do navegador.</p> +</div> + +<div class="blockIndicator note"> +<p><strong>Nota</strong>: As capturas de tela acima foram tiradas usando o <a href="/en-US/docs/Tools/Responsive_Design_Mode">Responsive Design Mode</a> no Firefox DevTools.</p> +</div> + +<p>À medida que a Web para dispositivos móveis começava a se tornar realidade com os primeiros telefones com essas características, empresas que desejavam adotar os dispositivos móveis geralmente criavam uma versão mobile do seu site, com uma URL diferente (geralmente algo como m.exemplo.com ou exemplo.mobi) Isso significava que duas versões separadas do site tinham que ser desenvolvidas e mantidas atualizadas.</p> + +<p>Além disso, esses sites para celular geralmente ofereciam uma experiência muito restrita. À medida que os dispositivos móveis se tornaram mais poderosos e capazes de exibir sites completos, os usuários de celular ficaram frustrados, pois, se viram presos na versão mobile do site e incapazes de acessar todas as informações que faziam parte da versão para desktop.</p> + +<h2 id="Layouts_flexiveis_antes_do_design_responsivo">Layouts flexiveis antes do design responsivo</h2> + +<p>Várias abordagens foram desenvolvidas para tentar resolver as desvantagens dos métodos de largura líquida ou largura fixa da construção de sites. Em 2004, Cameron Adams escreveu um artigo intitulado <a href="http://www.themaninblue.com/writing/perspective/2004/09/21/">Resolution dependent layout</a>, descrevendo um método para criar um design que pudesse se adaptar a diferentes resoluções de tela. Essa abordagem necessitava do JavaScript para detectar a resolução da tela e carregar o CSS correto.</p> + +<p>Zoe Mickley Gillenwater foi fundamental no <a href="http://zomigi.com/blog/voices-that-matter-slides-available/">seu trabalho</a> de descrever e formalizar as diferentes maneiras pelas quais sites flexíveis poderiam ser criados, tentando encontrar um meio termo entre preencher a tela ou ter tamanho completamente fixo.</p> + +<h2 id="Design_Responsivo">Design Responsivo</h2> + +<p>O termo design responsivo foi <a href="https://alistapart.com/article/responsive-web-design/">cunhado por Ethan Marcotte em 2010</a>, e descreveu o uso de três técnicas combinadas.</p> + +<ol> + <li>A primeira foi a ideia de grids fluidas, que já estava sendo explorada por Gillenwater, e pode ser encontrada no artigo de Marcotte, <a href="https://alistapart.com/article/fluidgrids/">Fluid Grids</a> (publicado em 2009 em A List Apart).</li> + <li>A segunda técnica foi a ideia de <a href="http://unstoppablerobotninja.com/entry/fluid-images">imagens fluidas</a>. Usando uma técnica muito simples que setava a propriedade <code>max-width</code> com <code>100%</code>, as imagens seriam reduzidas se a coluna que as continha se tornasse mais estreita que o tamanho intrínseco da imagem, mas nunca aumentariam. Isso permitiu que uma imagem fosse reduzida em tamanho para caber em uma coluna de tamanho flexível, em vez de transbordar, mas não aumentava e nem tornava-se pixelizada se a coluna fosse mais larga que a imagem.</li> + <li>O terceiro componente-chave foi a <a href="/en-US/docs/Web/CSS/Media_Queries">media query</a>. Media Queries habilitavam o tipo de opção de layout usando o JavaScript, que Cameron Adams havia explorado anteriormente, usando apenas CSS. Em vez de ter um layout para todos os tamanhos de tela, o layout podia ser alterado. As barras laterais podiam ser reposicionadas para a tela menor ou uma navegação alternativa podia ser exibida.</li> +</ol> + +<p>É importante entender que <strong>o design responsivo não é uma tecnologia separada</strong> — é um termo usado para descrever uma abordagem ao web design, ou um conjunto de melhores práticas, usado para criar um layout que possa <em>responder</em> ao dispositivo que está sendo usado para visualizar o conteúdo. Na exploração original de Marcotte, isso significava grades flexíveis (usando floats) e media queries, no entanto, nos últimos 10 anos, desde que o artigo foi escrito, trabalhar de forma responsiva se tornou um padrão. Os métodos de layout CSS modernos são inerentemente responsivos, e temos coisas novas incorporadas à plataforma web para facilitar o design de sites responsivos.</p> + +<p>O restante deste artigo indicará os vários recursos da plataforma web que você pode usar ao criar um site responsivo.</p> + +<h2 id="Media_Queries">Media Queries</h2> + +<p>O Design Responsivo apenas foi capaz de emergir devido o recurse de media query. A especificação Media Queries Level 3 se tornou uma Recomendação de Candidato em 2009, significando que estava pronto para ser implementado nos browsers. Media Queries nos permitem executar uma série de testes (e.g. se a tela do usuário é maior que uma certa largura, ou uma certa resolução) e aplicar um CSS seletivamente para estilizar a página de acordo com as necessidades do usuário.</p> + +<p>Por exemplo, a seguinte media querie testa se a página atual está sendo exibida como mídia de tela (portanto, não é um documento impresso) e o viewport tem pelo menos 800 pixels de largura. O CSS para o seletor <code>.container</code> será aplicado apenas se essas duas condições forem verdade.</p> + +<pre class="brush: css notranslate"><code>@media screen and (min-width: 800px) { + .container { + margin: 1em 2em; + } +} </code> +</pre> + +<p>Você pode adicionar múltiplos media queries dentro de uma folha de de estilo, ajustando inteiramente seu layout ou partes dele que melhor se adequem a vários tamanhos de tela. Os pontos em quem uma Media Query é introduzida e o layout alterado são conhecidos como <em>breakpoints</em>.</p> + +<p>Uma abordagem comum ao utilizar Media Queries é criar um layout de única coluna para dispositivos de telas pequenas (e.g smartphones), então fazer a checagem para telas maiores e implementar um layout de múltiplas colunas quando houver largura suficiente. Esse design é frequentemente descrito como <strong>mobile first</strong>.</p> + +<p>Encontre mais detalhes na documentação MDN para <a href="/en-US/docs/Web/CSS/Media_Queries">Media Queries</a>.</p> + +<h2 id="Grids_Flexíveis">Grids Flexíveis</h2> + +<p>Sites responsivos não apenas mudam seu layout entre <em>breakpoints</em>, eles são construídos em grids flexíveis. Um grid flexível significa que não há necessidade de marcar todos os tamanhos possíveis existentes, e sim, construir um layout perfeito baseado em pixels que se adequa automaticamente à tela. Essa abordagem seria impossível dado o vasto número de dispositivos com tamanhos diferentes que existem e o fato de que, mesmo nos desktops, as pessoas nem sempre utilizam a janela do navegador maximizada.</p> + +<p>Com o uso de um grid flexível, não há necessidade de adicionar um <em>breakpoint</em> e alterar o desing no ponto onde o conteúdo começa a parecer ruim em determinada tela. Por exemplo, se o comprimento da linha se torna ilegível à medida que o tamanho da tela aumenta, ou uma caixa se fica espremida com duas palavras em cada linha, conforme o tamanho diminui.</p> + +<p>Nos primórdios do design responsivo a única opção disponível para realizar layouts era utilizando <a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">floats</a>. Layouts flexíveis flutuantes eram alcançados dando a cada elemento uma largura percentual, garantindo que em todo layout os totais não fossem maior que 100%. In his original piece on fluid grids, Marcotte detailed a formula for taking a layout designed using pixels and converting it into percentages.</p> + +<pre class="notranslate"><code>target / context = result </code> +</pre> + +<p>For example if our target column size is 60 pixels, and the context (or container) it is in is 960 pixels, we divide 60 by 960 to get a value we can use in our CSS, after moving the decimal point two places to the right.</p> + +<pre class="brush: css notranslate"><code>.col { + width: 6.25%; /* 60 / 960 = 0.0625 */ +} </code> +</pre> + +<p>This approach will be found in many places across the web today, and it is documented here in the layout section of our <a href="/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods">Legacy layout methods</a> article. It is likely that you will come across websites using this approach in your work, so it is worth understanding it, even though you would not build a modern site using a float-based flexible grid.</p> + +<p>The following example demonstrates a simple responsive design using Media Queries and a flexible grid. On narrow screens the layout displays the boxes stacked on top of one another:</p> + +<figure><img alt="A mobile view of the layout with boxes stacked on top of each other vertically." src="https://mdn.mozillademos.org/files/16836/mdn-rwd-mobile.png" style="display: block; height: 407px; width: 300px;"> +<p>On wider screens they move to two columns:</p> + +<figcaption></figcaption> +</figure> + +<figure><img alt="A desktop view of a layout with two columns." src="https://mdn.mozillademos.org/files/16837/mdn-rwd-desktop.png" style="display: block; height: 217px; width: 600px;"> +<figcaption></figcaption> +</figure> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: You can find the <a href="https://mdn.github.io/css-examples/learn/rwd/float-based-rwd.html">live example</a> and <a href="https://github.com/mdn/css-examples/blob/master/learn/rwd/float-based-rwd.html">source code</a> for this example on GitHub.</p> +</div> + +<h2 id="Modern_layout_technologies">Modern layout technologies</h2> + +<p>Modern layout methods such as <a href="/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout">Multiple-column layout</a>, <a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a>, and <a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grid</a> are responsive by default. They all assume that you are trying to create a flexible grid and give you easier ways to do so.</p> + +<h3 id="Multicol">Multicol</h3> + +<p>The oldest of these layout methods is multicol — when you specify a <code>column-count</code>, this indicates how many columns you want your content to be split into. The browser then works out the size of these, a size that will change according to the screen size.</p> + +<pre class="brush: css notranslate"><code>.container { + column-count: 3; +} </code> +</pre> + +<p>If you instead specify a <code>column-width</code>, you are specifying a <em>minimum</em> width. The browser will create as many columns of that width as will comfortably fit into the container, then share out the remaining space between all the columns. Therefore the number of columns will change according to how much space there is.</p> + +<pre class="brush: css notranslate"><code>.container { + column-width: 10em; +} </code> +</pre> + +<h3 id="Flexbox">Flexbox</h3> + +<p>In Flexbox, flex items will shrink and distribute space between the items according to the space in their container, as their initial behavior. By changing the values for <code>flex-grow</code> and <code>flex-shrink</code> you can indicate how you want the items to behave when they encounter more or less space around them.</p> + +<p>In the example below the flex items will each take an equal amount of space in the flex container, using the shorthand of <code>flex: 1</code> as described in the layout topic <a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox#Flexible_sizing_of_flex_items">Flexbox: Flexible sizing of flex items</a>.</p> + +<pre class="brush: css notranslate"><code>.container { + display: flex; +} + +.item { + flex: 1; +} </code> +</pre> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: As an example we have rebuilt the simple responsive layout above, this time using flexbox. You can see how we no longer need to use strange percentage values to calculate the size of the columns: <a href="https://mdn.github.io/css-examples/learn/rwd/flex-based-rwd.html">example</a>, <a href="https://github.com/mdn/css-examples/blob/master/learn/rwd/flex-based-rwd.html">source code</a>.</p> +</div> + +<h3 id="CSS_grid">CSS grid</h3> + +<p>In CSS Grid Layout the <code>fr</code> unit allows the distribution of available space across grid tracks. The next example creates a grid container with three tracks sized at <code>1fr</code>. This will create three column tracks, each taking one part of the available space in the container. You can find out more about this approach to create a grid in the Learn Layout Grids topic, under <a href="en-US/docs/Learn/CSS/CSS_layout/Grids#Flexible_grids_with_the_fr_unit">Flexible grids with the fr unit</a>.</p> + +<pre class="brush: css notranslate"><code>.container { + display: grid; + grid-template-columns: 1fr 1fr 1fr; +} </code> +</pre> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: The grid layout version is even simpler as we can define the columns on the .wrapper: <a href="https://mdn.github.io/css-examples/learn/rwd/grid-based-rwd.html">example</a>, <a href="https://github.com/mdn/css-examples/blob/master/learn/rwd/grid-based-rwd.html">source code</a>.</p> +</div> + +<h2 id="Responsive_images">Responsive images</h2> + +<p>The simplest approach to responsive images was as described in Marcotte's early articles on responsive design. Basically, you would take an image that was at the largest size that might be needed, and scale it down. This is still an approach used today, and in most stylesheets you will find the following CSS somewhere:</p> + +<pre class="brush: css notranslate"><code>img { + max-width: 100%: +} </code> +</pre> + +<p>There are obvious downsides to this approach. The image might be displayed a lot smaller than its intrinsic size, which is a waste of bandwidth — a mobile user may be downloading an image several times the size of what they actually see in the browser window. In addition, you may not want the same image aspect ratio on mobile as on desktop. For example, it might be nice to have a square image for mobile, but show the same scene as a landscape image on desktop. Or, acknowledging the smaller size of an image on mobile you might want to show a different image altogether, one which is more easily understood at a small screen size. These things can't be achieved by simply scaling down an image.</p> + +<p>Responsive Images, using the <code><a href="/en-US/docs/Web/HTML/Element/picture"><picture></a></code> element and the <code><a href="/en-US/docs/Web/HTML/Element/img"><img></a></code> <code>srcset</code> and <code>sizes</code> attributes solve both of these problems. You can provide multiple sizes along with "hints" (meta data that describes the screen size and resolution the image is best suited for), and the browser will choose the most appropriate image for each device, ensuring that a user will download an image size appropriate for the device they are using.</p> + +<p>You can also <em>art direct</em> images used at different sizes, thus providing a different crop or completely different image to different screen sizes.</p> + +<p>You can find a detailed <a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images">guide to Responsive Images in the Learn HTML section</a> here on MDN.</p> + +<h2 id="Responsive_typography">Responsive typography</h2> + +<p>An element of responsive design not covered in earlier work was the idea of responsive typography. Essentially, this describes changing font sizes within media queries to reflect lesser or greater amounts of screen real estate.</p> + +<p>In this example, we want to set our level 1 heading to be <code>4rem</code>, meaning it will be four times our base font size. That's a really large heading! We only want this jumbo heading on larger screen sizes, therefore we first create a smaller heading then use media queries to overwrite it with the larger size if we know that the user has a screen size of at least 1200px.</p> + +<pre class="brush: css notranslate"><code>html { + font-size: 1em; +} + +h1 { + font-size: 2rem; +} + +@media (min-width: 1200px) { + h1 { + font-size: 4rem; + } +} </code> +</pre> + +<p>We have edited our responsive grid example above to also include responsive type using the method outlined. You can see how the heading switches sizes as the layout goes to the two column version.</p> + +<p>On mobile the heading is smaller:</p> + +<figure><img alt="A stacked layout with a small heading size." src="https://mdn.mozillademos.org/files/16838/mdn-rwd-font-mobile.png" style="display: block; height: 407px; width: 300px;"> +<p>On desktop however we see the larger heading size:</p> + +<figcaption></figcaption> +</figure> + +<figure><img alt="A two column layout with a large heading." src="https://mdn.mozillademos.org/files/16839/mdn-rwd-font-desktop.png" style="display: block; height: 169px; width: 600px;"> +<figcaption></figcaption> +</figure> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: See this example in action: <a href="https://mdn.github.io/css-examples/learn/rwd/type-rwd.html">example</a>, <a href="https://github.com/mdn/css-examples/blob/master/learn/rwd/type-rwd.html">source code</a>.</p> +</div> + +<p>As this approach to typography shows, you do not need to restrict media queries to only changing the layout of the page. They can be used to tweak any element to make it more usable or attractive at alternate screen sizes.</p> + +<h3 id="Using_viewport_units_for_responsive_typography">Using viewport units for responsive typography</h3> + +<p>An interesting approach is to use the viewport unit <code>vw</code> to enable responsive typography. <code>1vw</code> is equal to one percent of the viewport width, meaning that if you set your font size using <code>vw</code>, it will always relate to the size of the viewport.</p> + +<pre class="brush: css notranslate">h1 { + font-size: 6vw; +}</pre> + +<p>The problem with doing the above is that the user loses the ability to zoom any text set using the vw unit, as that text is always related to the size of the viewport. <strong>Therefore you should never set text using viewport units alone</strong>.</p> + +<p>There is a solution, and it involves using <code><a href="/en-US/docs/Web/CSS/calc">calc()</a></code>. If you add the <code>vw</code> unit to a value set using a fixed size such as <code>em</code>s or <code>rem</code>s then the text will still be zoomable. Essentially, the <code>vw</code> unit adds on top of that zoomed value:</p> + +<pre class="brush: css notranslate">h1 { + font-size: calc(1.5rem + 3vw); +}</pre> + +<p>This means that we only need to specify the font size for the heading once, rather than set it up for mobile and redefine it in the media queries. The font then gradually increases as you increase the size of the viewport.</p> + +<div class="blockIndicator note"> +<p>See an example of this in action: <a href="https://mdn.github.io/css-examples/learn/rwd/type-vw.html">example</a>, <a href="https://github.com/mdn/css-examples/blob/master/learn/rwd/type-vw.html">source code</a>.</p> +</div> + +<h2 id="The_viewport_meta_tag">The viewport meta tag</h2> + +<p>If you look at the HTML source of a responsive page, you will usually see the following {{htmlelement("meta")}} tag in the <code><head></code> of the document.</p> + +<pre class="brush: html notranslate"><code><meta name="viewport" content="width=device-width,initial-scale=1"></code> +</pre> + +<p>This meta tag tells mobile browsers that they should set the width of the viewport to the device width, and scale the document to 100% of its intended size, which shows the document at the mobile-optimized size that you intended.</p> + +<p>Why is this needed? Because mobile browsers tend to lie about their viewport width.</p> + +<p>This meta tag exists because when the original iPhone launched and people started to view websites on a small phone screen, most sites were not mobile optimized. The mobile browser would therefore set the viewport width to 960 pixels, render the page at that width, and show the result as a zoomed-out version of the desktop layout. Other mobile browsers (e.g. on Google Android) did the same thing. Users could zoom in and pan around the website to view the bits they were interested in, but it looked bad. You will still see this today if you have the misfortune to come across a site that does not have a responsive design.</p> + +<p>The trouble is that your responsive design with breakpoints and media queries won't work as intended on mobile browsers. If you've got a narrow screen layout that kicks in at 480px viewport width or less, and the viewport is set at 960px, you'll never see your narrow screen layout on mobile. By setting <code>width=device-width</code> you are overriding Apple's default <code>width=960px</code> with the actual width of the device, so your media queries will work as intended.</p> + +<p><strong>So you should <em>always</em> include the above line of HTML in the head of your documents.</strong></p> + +<p>There are other settings you can use with the viewport meta tag, however in general the above line is what you will want to use.</p> + +<ul> + <li><code>initial-scale</code>: Sets the initial zoom of the page, which we set to 1.</li> + <li><code>height</code>: Sets a specific height for the viewport.</li> + <li><code>minimum-scale</code>: Sets the minimum zoom level.</li> + <li><code>maximum-scale</code>: Sets the maximum zoom level.</li> + <li><code>user-scalable</code>: Prevents zooming if set to <code>no</code>.</li> +</ul> + +<p>You should avoid using <code>minimum-scale</code>, <code>maximum-scale</code>, and in particular setting <code>user-scalable</code> to <code>no</code>. Users should be allowed to zoom as much or as little as they need to; preventing this causes accessibility problems.</p> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: There is a CSS @ rule designed to replace the viewport meta tag — <a href="/en-US/docs/Web/CSS/@viewport">@viewport</a> — however it has poor browser support. It was implemented in Internet Explorer and Edge, however once the Chromium-based Edge ships it will no longer be part of the Edge browser.</p> +</div> + +<h2 id="Summary">Summary</h2> + +<p>Responsive design refers to a site or application design that responds to the environment in which it is viewed. It encompasses a number of CSS and HTML features and techniques, and is now essentially just how we build websites by default. Consider the sites that you visit on your phone — it is probably fairly unusual to come across a site that is the desktop version scaled down, or where you need to scroll sideways to find things. This is because the web has moved to this approach of designing responsively.</p> + +<p>It has also become much easier to achieve responsive designs with the help of the layout methods you have learned in these lessons. If you are new to web development today you have many more tools at your disposal than in the early days of responsive design. It is therefore worth checking the age of any materials you are referencing. While the historical articles are still useful, modern use of CSS and HTML makes it far easier to create elegant and useful designs, no matter what device your visitor views the site with.</p> + +<p>{{PreviousMenuNext("Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout/Media_queries", "Learn/CSS/CSS_layout")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Introduction">Introduction to CSS layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Normal_Flow">Normal flow</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grid</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">Floats</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">Positioning</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout">Multiple-column layout</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design">Responsive design</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Media_queries">Beginner's guide to media queries</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods">Legacy layout methods</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Supporting_Older_Browsers">Supporting older browsers</a></li> + <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension">Fundamental layout comprehension assessment</a></li> +</ul> |