2009-07-28 18 views

Respuesta

62

Usted puede tener un elemento con posición absoluta interior de su elemento posicionado relativo:

<div id="container"> 
    <div id="background"> 
    Text to have as background 
    </div> 
    Normal contents 
</div> 

Y entonces el CSS:

#container { 
    position: relative; 
} 

#background { 
    position: absolute; 
    top: 0; 
    left: 0; 
    bottom: 0; 
    right: 0; 
    z-index: -1; 
    overflow: hidden; 
} 

Aquí es an example of it.

+4

elementName: tras { \t contenido: "\ BB"; \t flotador: derecho; } – Jazzy

1

Puede hacer que el elemento que contiene el texto bg tenga un orden de apilamiento menor (índice z, posición) e incluso posiblemente establezca la opacidad. Por lo tanto, el elemento que necesita en la parte superior necesitaría un orden de apilamiento superior (z-index: 5; position: relative; por ejemplo) y el elemento de atrás necesitaría algo menor (por defecto o solo un índice z más bajo como 3 y posición: relativo ;).

34

Puede ser posible (pero muy hacker), con sólo CSS usando el: before o: after pseudo elementos:

<style type="text/css"> 
    .bgtext { 
    position: relative; 
    } 
    .bgtext:after { 
    content: "Background text"; 
    position: absolute; 
    top: 0; 
    left: 0; 
    z-index: -1; 
    } 
</style> 

<div class="bgtext"> 
    Foreground text 
</div> 

Esto parece funcionar, pero probablemente tendrá que ajustar un poco. También tenga en cuenta que no funcionará en IE6 porque no es compatible con :after.

+0

Actualización: Por ahora, todos los navegadores modernos admiten pseudo-elementos. Por ejemplo, así es como funciona FontAwesome para los iconos de CSS (usando: antes en los elementos en línea). –

82

¿Qué tal un imagen de fondo de texto SVG?

body { 
 
    background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='red' font-size='20'>I love SVG!</text></svg>"); 
 
}
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p> 
 
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p>

versión sangría de CSS para que pueda entender mejor (esto no trabajo, es necesario utilizar el sencillo forro SVG):

body { 
    background-image:url("data:image/svg+xml;utf8, 
    <svg xmlns='http://www.w3.org/2000/svg' version='1.1' 
     height='50px' width='120px'> 
    <text x='0' y='15' fill='red' font-size='20'>I love SVG!</text> 
    </svg>"); 
} 
No

seguro de cómo portable, esto es (funciona en Firefox 31 y Chrome 36), y técnicamente es una imagen ... pero la fuente está en línea y en texto plano, y se amplía infinitamente.

@senectus encontró que funciona mejor en base 64 es decir, si codificarlo: https://stackoverflow.com/a/25593531/895245

+0

Interesante. Solo pude hacer que esto funcionara en Firefox 31, pero no en Chrome 36 o Safari 7. –

+0

@JPRichardson Cierto, lo mismo aquí. En Chrome 36 tengo la impresión de que el fondo está allí, pero en * muy * minúsculas. Tal vez me estoy olvidando de establecer algunos fondo/parámetro de tamaño SVG? –

+0

Ya, estoy experimentando con él en este momento ... parece que tal vez "viewBox"? Todavía estoy jugando con eso. –

13

solución de Ciro sobre un fondo SVG URI de datos que contiene el texto es muy inteligente.

Sin embargo, no funcionará en IE si solo agrega la fuente SVG normal al URI de datos.

Para evitar esto y hacerlo funcionar en IE9 en adelante, codifique el SVG a base64. This is a great tool.

Así que esto:

background:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><text x="5%" y="5%" font-size="30" fill="red">I love SVG!</text></svg>'); 

Se convierte en esto:

background:url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0ZXh0IHg9IjUlIiB5PSI1JSIgZm9udC1zaXplPSIzMCIgZmlsbD0icmVkIj5JIGxvdmUgU1ZHITwvdGV4dD48L3N2Zz4='); 

probado y que funciona en IE9-10-11, WebKit (Chrome 37, Opera 23) y Gecko (Firefox 31) .

http://jsfiddle.net/qapp5dLn/

+0

Esta es una herramienta mejor: https://jpillora.com/base64-encoder/ simpile, sin errores, autocompletado, previsualización de imágenes. Sí, es mejor a pasos agigantados. –

1

@Ciro

Puede romper el código en línea con SVG barra invertida "\"

Probado con el código de abajo en Chrome 54 y Firefox 50

body { 
    background: transparent; 
    background-attachment:fixed; 
    background-image: url(
    "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \ 
    <rect x='0' y='0' width='170' height='50' style='stroke:white; fill:gray; stroke-opacity: 0.3; stroke-width: 3px; fill-opacity: 0.7; stroke-dasharray: 10 5; stroke-linecap=round; '/> \ 
    <text x='85' y='30' style='fill:lightBlue; text-anchor: middle' font-size='16' transform='rotate(10,85,25)'>I love SVG!</text></svg>"); 
} 

I incluso Probó esto,

background-image: url("\ 
data:image/svg+xml;utf8, \ 
    <svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \ 
    <rect x='0' y='0' width='170' height='50'\ 
     style='stroke:white; stroke-width: 3px; stroke-opacity: 0.3; \ 
      stroke-dasharray: 10 5; stroke-linecap=round; \ 
      fill:gray; fill-opacity: 0.7; '/> \ 
    <text x='85' y='30' \ 
     style='fill:lightBlue; text-anchor: middle' font-size='16' \ 
     transform='rotate(10,85,25)'> \ 
     I love SVG! \ 
    </text> \ 
    </svg>\ 
"); 

y funciona (al menos en Chrome 54 & Firefox 50 ==> su uso en NWjs & Electrón guarenteed)

0

El uso de CSS puro:

(Sin embargo, utilizar esto en raras ocasiones, porque el método HTML es mucho PREFERIDO, entonces esto).

.container{ 
 
\t position:relative; 
 
} 
 
.container::before{ 
 
\t content:""; 
 
\t width: 100%; height: 100%; position: absolute; background: black; opacity: 0.3; z-index: 1; top: 0; left: 0; 
 
\t background: black; 
 
} 
 
.container::after{ 
 
\t content: "Your Text"; position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 3; overflow: hidden; font-size: 2em; color: red; text-align: center; text-shadow: 0px 0px 5px black; background: #0a0a0a8c; padding: 5px; 
 
\t animation-name: blinking; 
 
\t animation-duration: 1s; 
 
\t animation-iteration-count: infinite; 
 
\t animation-direction: alternate; 
 
} 
 
@keyframes blinking { 
 
\t 0% {opacity: 0;} 
 
\t 100% {opacity: 1;} 
 
}
<div class="container">here is main content, text , <br/> images and other page details</div>

Cuestiones relacionadas