Fundo CSS
- Página anterior Criação CSS
- Próxima página Texto CSS
O CSS permite aplicar cores puras como fundo, também permite usar imagens de fundo para criar efeitos bastante complexos.
A capacidade do CSS nessa área é muito superior ao HTML.
Cor de fundo
Pode ser usado Propriedade background-colorDefinir a cor de fundo do elemento. Esta propriedade aceita qualquer valor de cor válido.
Esta regra define o fundo do elemento como cinza:
p {background-color: gray;}
Se você deseja que a cor de fundo se estenda pouco para fora do texto do elemento, apenas aumente um pouco o espaçamento interno:
p {background-color: gray; padding: 20px;}
É possível definir a cor de fundo para todos os elementos, incluindo body até elementos inline como em e a.
background-color não pode ser herdado, seu valor padrão é transparente. Transparente significa 'transparente'. Isso é, se um elemento não especificar uma cor de fundo, o fundo será transparente, permitindo que o fundo do elemento ancestral seja visível.
imagem de fundo
Para inserir uma imagem de fundo, é necessário usar Propriedade background-image.O valor padrão da propriedade background-image é none, o que significa que não há nenhuma imagem colocada no fundo.
Se precisar definir uma imagem de fundo, é necessário definir um valor de URL para essa propriedade:
body {background-image: url(/i/eg_bg_04.gif);}
A maioria dos fundos são aplicados ao elemento body, mas não se limita a isso.
O exemplo a seguir aplica um fundo a um parágrafo sem aplicar fundo a outras partes do documento:
p.flower {background-image: url(/i/eg_bg_03.gif);}
Você até pode definir uma imagem de fundo para elementos inline. O exemplo a seguir define uma imagem de fundo para um link:
a.radio {background-image: url(/i/eg_bg_07.gif);}
Teoricamente, você pode aplicar imagens de fundo a elementos substitutivos como textareas e select, mas nem todos os agentes de usuário lidam bem com essa situação.
Além disso, é importante notar que background-image não pode ser herdado. De fato, todas as propriedades de fundo não podem ser herdadas.
Repetição de fundo
Se precisar de fundo repetido na página, você pode usar Propriedade background-repeat.
O valor da propriedade repeat faz com que a imagem se repita tanto na horizontal quanto na vertical, como era comum na imagem de fundo anterior. repeat-x e repeat-y fazem com que a imagem se repita apenas na horizontal ou na vertical, enquanto no-repeat não permite que a imagem se repita em nenhuma direção.
Por padrão, a imagem de fundo começará no canto superior esquerdo de um elemento. Veja o exemplo a seguir:
body { background-image: url(/i/eg_bg_03.gif); background-repeat: repeat-y; }
Posicionamento de fundo
Você pode usar Propriedade background-positionMudar a posição da imagem no fundo.
O exemplo a seguir coloca uma imagem de fundo no centro do elemento body:
body { background-image:url('/i/eg_bg_03.gif'); background-repeat:no-repeat; background-position: center; }
Existem muitos métodos para fornecer valores para a propriedade background-position. Primeiro, você pode usar algumas palavras-chave: top, bottom, left, right e center. Normalmente, essas palavras-chave aparecem em pares, mas nem sempre é assim. Você também pode usar valores de comprimento, como 100px ou 5cm, e, por fim, também pode usar valores em porcentagem. Valores de diferentes tipos diferem ligeiramente na posição da imagem de fundo.
Palavras-chave
As palavras-chave de colocação de imagem são as mais fáceis de entender, suas funções são como indicadas pelos nomes. Por exemplo, top right coloca a imagem no canto superior direito da área de margem interna do elemento.
Segundo a norma, as palavras-chave de posição podem aparecer em qualquer ordem, desde que não ultrapassem duas palavras-chave - uma para a direção horizontal e outra para a direção vertical.
Se apenas uma palavra-chave aparecer, considera-se que a outra palavra-chave é center.
Portanto, se você desejar que uma imagem apareça no meio superior de cada parágrafo, basta declarar assim:
p { background-image:url('bgimg.gif'); background-repeat:no-repeat; background-position:top; }
A seguir estão as palavras-chave de posição equivalentes:
Palavra-chave única | Palavras-chave equivalentes |
---|---|
center | center center |
top | top center ou center top |
bottom | bottom center ou center bottom |
right | right center ou center right |
left | left center ou center left |
Valores percentuais
A representação dos valores percentuais é mais complexa. Suponha que você queira usar valores percentuais para centralizar uma imagem dentro do elemento, isso é fácil:
body { background-image:url('/i/eg_bg_03.gif'); background-repeat:no-repeat; background-position:50% 50%; }
Isso resulta na imagem sendo colocada adequadamente, com seu centro alinhado com o centro do elemento.Em outras palavras, os valores percentuais são aplicados tanto ao elemento quanto à imagem.Isso significa que o ponto descrito como 50% 50% na imagem (ponto central) alinha-se com o ponto descrito como 50% 50% no elemento (ponto central).
Se a imagem estiver em 0% 0%, seu canto superior esquerdo ficará no canto superior esquerdo da área de margem interna do elemento. Se a posição da imagem for 100% 100%, o canto inferior direito da imagem ficará no canto inferior direito da margem direita.
Portanto, se você quiser colocar uma imagem no ponto 2/3 horizontalmente e 1/3 verticalmente, pode declarar assim:
body { background-image:url('/i/eg_bg_03.gif'); background-repeat:no-repeat; background-position:66% 33%; }
Se apenas um valor percentual for fornecido, esse valor será usado como valor horizontal, e o valor vertical será suposto ser 50%. Isso é semelhante a palavras-chave.
O valor padrão de background-position é 0% 0%, o que é equivalente a top left em termos funcionais. Isso explica por que a imagem de fundo sempre começa a ser repetida a partir do canto superior esquerdo da área de margem interna do elemento, a menos que você defina valores de posição diferentes.
Length values
Length values explain the offset from the top-left corner of the padding area of the element. The offset point is the top-left corner of the image.
For example, if the value is set to 50px 100px, the top-left corner of the image will be 50 pixels to the right and 100 pixels down from the top-left corner of the padding area of the element:
body { background-image:url('/i/eg_bg_03.gif'); background-repeat:no-repeat; background-position:50px 100px; }
Note that this is different from percentage values, because the offset is only from one top-left corner to another top-left corner. That is, the top-left corner of the image aligns with the point specified in the background-position declaration.
Background association
If the document is long, then when the document scrolls down, the background image will also scroll. When the document scrolls past the position of the image, the image will disappear.
You can use background-attachment propertyPrevent this scrolling. Through this property, you can declare that the image is fixed relative to the visible area (fixed), so it is not affected by scrolling:
body { background-image:url(/i/eg_bg_02.gif); background-repeat:no-repeat; background-attachment:fixed }
The default value of the background-attachment property is scroll, which means that by default, the background will scroll with the document.
CSS Background Example
- Set the background color
- This example demonstrates how to set the background color for an element.
- Set the background color of the text
- This example shows how to set the background color of part of the text.
- Set image as background
- This example demonstrates how to set an image as the background.
- Set image as background 2
- This example demonstrates how to set a background image for multiple elements at the same time.
- How to repeat the background image
- This example demonstrates how to repeat the background image.
- How to repeat the background image vertically
- This example demonstrates how to repeat the background image vertically.
- How to repeat the background image horizontally
- This example demonstrates how to repeat the background image horizontally.
- How to display the background image only once
- This example demonstrates how to display the background image only once.
- How to place the background image
- This example demonstrates how to place the background image on the page.
- How to position the background image using %
- This example demonstrates how to use percentages to position the background image on the page.
- How to position the background image using pixels
- This example demonstrates how to use pixels to position the background image on the page.
- How to set a fixed background image
- This example demonstrates how to set a fixed background image. The image will not scroll with the other parts of the page.
- All background properties in one declaration
- Este exemplo demonstra como usar a propriedade abreviada para definir todas as propriedades de fundo em uma declaração.
Propriedades de fundo CSS
Propriedade | Descrição |
---|---|
background | Propriedade abreviada, que coloca a propriedade de fundo em uma declaração. |
background-attachment | Se a imagem de fundo deve ser fixa ou rolar com o resto da página. |
background-color | Configurar a cor de fundo do elemento. |
background-image | Configurar a imagem como fundo. |
background-position | Configurar a posição inicial da imagem de fundo. |
background-repeat | Configurar se a imagem de fundo deve ser repetida e como. |
- Página anterior Criação CSS
- Próxima página Texto CSS