Skip to content

Commit b0a578c

Browse files
authored
Merge pull request #426 from MoisesTR/patch-1
Shadow DOM styling
2 parents d406053 + 7d4fb40 commit b0a578c

File tree

1 file changed

+63
-63
lines changed

1 file changed

+63
-63
lines changed

8-web-components/6-shadow-dom-style/article.md

Lines changed: 63 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
# Shadow DOM styling
1+
# Estilo Shadow DOM
22

3-
Shadow DOM may include both `<style>` and `<link rel="stylesheet" href="…">` tags. In the latter case, stylesheets are HTTP-cached, so they are not redownloaded for multiple components that use same template.
3+
Shadow DOM puede incluir las etiquetas `<style>` y `<link rel="stylesheet" href="…">`. En este último caso, las hojas de estilo se almacenan en la caché HTTP, por lo que no se vuelven a descargar para varios de los componentes que usan la misma plantilla.
44

5-
As a general rule, local styles work only inside the shadow tree, and document styles work outside of it. But there are few exceptions.
5+
Como regla general, los estilos locales solo funcionan dentro del shadow tree, y los estilos de documentos funcionan fuera de él. Pero hay pocas excepciones.
66

77
## :host
88

9-
The `:host` selector allows to select the shadow host (the element containing the shadow tree).
9+
El selector `:host` permite seleccionar el shadow host (el elemento que contiene el shadow tree).
1010

11-
For instance, we're making `<custom-dialog>` element that should be centered. For that we need to style the `<custom-dialog>` element itself.
11+
Por ejemplo, estamos creando un elemento `<custom-dialog>` que debería estar centrado. Para eso necesitamos diseñar el elemento `<custom-dialog>`.
1212

13-
That's exactly what `:host` does:
13+
Eso es exactamente lo que `:host` hace:
1414

1515
```html run autorun="no-epub" untrusted height=80
1616
<template id="tmpl">
1717
<style>
18-
/* the style will be applied from inside to the custom-dialog element */
18+
/* el estilo se aplicará desde el interior al elemento de diálogo personalizado */
1919
:host {
2020
position: fixed;
2121
left: 50%;
@@ -42,32 +42,32 @@ customElements.define('custom-dialog', class extends HTMLElement {
4242
</custom-dialog>
4343
```
4444

45-
## Cascading
45+
## Cascada
4646

47-
The shadow host (`<custom-dialog>` itself) resides in the light DOM, so it's affected by document CSS rules.
47+
El shadow host (`<custom-dialog>` en sí) reside en el light DOM, por lo que se ve afectado por las reglas de CSS del documento.
4848

49-
If there's a property styled both in `:host` locally, and in the document, then the document style takes precedence.
49+
Si hay una propiedad con estilo tanto en el `:host` localmente, y en el documento, entonces el estilo del documento tiene prioridad.
5050

51-
For instance, if in the document we had:
51+
Por ejemplo, si en el documento tenemos:
5252
```html
5353
<style>
5454
custom-dialog {
5555
padding: 0;
5656
}
5757
</style>
5858
```
59-
...Then the `<custom-dialog>` would be without padding.
59+
...Entonces el `<custom-dialog>` estaría sin padding.
6060

61-
It's very convenient, as we can setup "default" component styles in its `:host` rule, and then easily override them in the document.
61+
Es muy conveniente, ya que podemos configurar estilos de componentes "predeterminados" en su regla `:host`, y luego sobreescribirlos fácilmente en el documento.
6262

63-
The exception is when a local property is labelled `!important`, for such properties, local styles take precedence.
63+
La excepción es cuando una propiedad local está etiquetada como `!important`. Para tales propiedades, los estilos locales tienen prioridad.
6464

6565

6666
## :host(selector)
6767

68-
Same as `:host`, but applied only if the shadow host matches the `selector`.
68+
Igual que `:host`, pero se aplica solo si el shadow host coincide con el `selector`.
6969

70-
For example, we'd like to center the `<custom-dialog>` only if it has `centered` attribute:
70+
Por ejemplo, nos gustaría centrar el `<custom-dialog>` solo si tiene el atributo `centered`:
7171

7272
```html run autorun="no-epub" untrusted height=80
7373
<template id="tmpl">
@@ -101,40 +101,40 @@ customElements.define('custom-dialog', class extends HTMLElement {
101101

102102

103103
<custom-dialog centered>
104-
Centered!
104+
¡Centrado!
105105
</custom-dialog>
106106

107107
<custom-dialog>
108-
Not centered.
108+
No centrado.
109109
</custom-dialog>
110110
```
111111

112-
Now the additional centering styles are only applied to the first dialog: `<custom-dialog centered>`.
112+
Ahora los estilos de centrado adicionales solo se aplican al primer diálogo: `<custom-dialog centered>`.
113113

114114
## :host-context(selector)
115115

116-
Same as `:host`, but applied only if the shadow host or any of its ancestors in the outer document matches the `selector`.
116+
Igual que `:host`, pero se aplica solo si el shadow host o cualquiera de sus ancestros en el documento exterior coinciden con el `selector`.
117117

118-
E.g. `:host-context(.dark-theme)` matches only if there's `dark-theme` class on `<custom-dialog>` on anywhere above it:
118+
p. ej. `:host-context(.dark-theme)` coincide solo si hay una clase `dark-theme` en `<custom-dialog>` en cualquier lugar por encima de el:
119119

120120
```html
121121
<body class="dark-theme">
122122
<!--
123-
:host-context(.dark-theme) applies to custom-dialogs inside .dark-theme
123+
:host-context(.dark-theme) se aplica a los custom-dialogs dentro de .dark-theme
124124
-->
125125
<custom-dialog>...</custom-dialog>
126126
</body>
127127
```
128128

129-
To summarize, we can use `:host`-family of selectors to style the main element of the component, depending on the context. These styles (unless `!important`) can be overridden by the document.
129+
Para resumir, podemos usar `:host`-familia de selectores para aplicar estilos al elemento principal del componente, según el contexto. Estos estilos (a menos que sea `!important`) pueden ser sobreescritos por el documento.
130130

131-
## Styling slotted content
131+
## Estilo de contenido eslotado(cuando un elemento ha sido insertado en un slot, se dice que fue eslotado por su término en inglés slotted)
132132

133-
Now let's consider the situation with slots.
133+
Ahora consideremos la situación con los slots.
134134

135-
Slotted elements come from light DOM, so they use document styles. Local styles do not affect slotted content.
135+
Los elementos eslotados vienen del light DOM, por lo que usan estilos del documento. Los estilos locales no afectan al contenido de los elementos eslotados.
136136

137-
In the example below, slotted `<span>` is bold, as per document style, but does not take `background` from the local style:
137+
En el siguiente ejemplo, el elemento eslotado `<span>` está en bold, según el estilo del documento, pero no toma el `background` del estilo local:
138138
```html run autorun="no-epub" untrusted height=80
139139
<style>
140140
*!*
@@ -163,11 +163,11 @@ customElements.define('user-card', class extends HTMLElement {
163163
</script>
164164
```
165165
166-
The result is bold, but not red.
166+
El resultado es bold, pero no red.
167167
168-
If we'd like to style slotted elements in our component, there are two choices.
168+
Si queremos aplicar estilos a elementos eslotados en nuestro componente, hay dos opciones.
169169
170-
First, we can style the `<slot>` itself and rely on CSS inheritance:
170+
Primero, podemos aplicarle el estilo al elemento `<slot>` en sí mismo y confiar en la herencia CSS:
171171
172172
```html run autorun="no-epub" untrusted height=80
173173
<user-card>
@@ -191,14 +191,14 @@ customElements.define('user-card', class extends HTMLElement {
191191
</script>
192192
```
193193
194-
Here `<p>John Smith</p>` becomes bold, because CSS inheritance is in effect between the `<slot>` and its contents. But in CSS itself not all properties are inherited.
194+
Aquí `<p>John Smith</p>` se vuelve bold, porque la herencia CSS está en efecto entre el `<slot>` y su contenido. Pero en el propio CSS no todas las propiedades se heredan.
195195
196-
Another option is to use `::slotted(selector)` pseudo-class. It matches elements based on two conditions:
196+
Otra opción es usar la pseudoclase `::slotted(selector)`. Coincide con elementos en función de 2 condiciones.
197197
198-
1. That's a slotted element, that comes from the light DOM. Slot name doesn't matter. Just any slotted element, but only the element itself, not its children.
199-
2. The element matches the `selector`.
198+
1. Eso es un elemento eslotado, que viene del light DOM. El nombre del slot no importa. Cualquier elemento eslotado, pero solo el elemento en si, no sus hijos.
199+
2. El elemento coincide con el `selector`.
200200
201-
In our example, `::slotted(div)` selects exactly `<div slot="username">`, but not its children:
201+
En nuestro ejemplo, `::slotted(div)` selecciona exactamente `<div slot="username">`, pero no sus hijos:
202202
203203
```html run autorun="no-epub" untrusted height=80
204204
<user-card>
@@ -224,54 +224,54 @@ customElements.define('user-card', class extends HTMLElement {
224224
</script>
225225
```
226226
227-
Please note, `::slotted` selector can't descend any further into the slot. These selectors are invalid:
227+
Tenga en cuenta, que el selector `::slotted` no puede descender más en el slot. Estos selectores no son válidos:
228228
229229
```css
230230
::slotted(div span) {
231-
/* our slotted <div> does not match this */
231+
/* nuestro slotted <div> no coincide con esto */
232232
}
233233
234234
::slotted(div) p {
235-
/* can't go inside light DOM */
235+
/* No puede entrar en light DOM */
236236
}
237237
```
238238
239-
Also, `::slotted` can only be used in CSS. We can't use it in `querySelector`.
239+
También, `::slotted` solo se puede utilizar en CSS. No podemos usarlo en `querySelector`.
240240
241-
## CSS hooks with custom properties
241+
## CSS hooks con propiedades personalizadas
242242
243-
How do we style internal elements of a component from the main document?
243+
¿Cómo diseñamos los elementos internos de un componente del documento principal?
244244
245-
Selectors like `:host` apply rules to `<custom-dialog>` element or `<user-card>`, but how to style shadow DOM elements inside them?
245+
Selectores como `:host` aplican reglas al elemento `<custom-dialog>` o `<user-card>`, ¿pero cómo aplicar estilos a elementos del shadow DOM dentro de ellos?
246246
247-
There's no selector that can directly affect shadow DOM styles from the document. But just as we expose methods to interact with our component, we can expose CSS variables (custom CSS properties) to style it.
247+
No hay ningún selector que pueda afectar directamente a los estilos del shadow DOM del documento. Pero así como exponemos métodos para interactuar con nuestro componente, podemos exponer variables CSS (propiedades CSS personalizadas) para darle estilo.
248248
249-
**Custom CSS properties exist on all levels, both in light and shadow.**
249+
**Existen propiedades CSS personalizadas en todos los niveles, tanto en light como shadow.**
250250
251-
For example, in shadow DOM we can use `--user-card-field-color` CSS variable to style fields, and the outer document can set its value:
251+
Por ejemplo, en el shadow DOM podemos usar la variable CSS `--user-card-field-color` para dar estilo a los campos, y en el documento exterior establecer su valor:
252252
253253
```html
254254
<style>
255255
.field {
256256
color: var(--user-card-field-color, black);
257-
/* if --user-card-field-color is not defined, use black color */
257+
/* si --user-card-field-color no esta definido, usar color negro */
258258
}
259259
</style>
260260
<div class="field">Name: <slot name="username"></slot></div>
261261
<div class="field">Birthday: <slot name="birthday"></slot></div>
262262
```
263263

264-
Then, we can declare this property in the outer document for `<user-card>`:
264+
Entonces, podemos declarar esta propiedad en el documento exterior para `<user-card>`:
265265

266266
```css
267267
user-card {
268268
--user-card-field-color: green;
269269
}
270270
```
271271

272-
Custom CSS properties pierce through shadow DOM, they are visible everywhere, so the inner `.field` rule will make use of it.
272+
Las propiedades personalizadas CSS atraviesan el shadow DOM, son visibles en todas partes, por lo que la regla interna `.field` hará uso de ella.
273273

274-
Here's the full example:
274+
Aquí está el ejemplo completo:
275275

276276
```html run autorun="no-epub" untrusted height=80
277277
<style>
@@ -311,24 +311,24 @@ customElements.define('user-card', class extends HTMLElement {
311311
312312
313313
314-
## Summary
314+
## Resumen
315315
316-
Shadow DOM can include styles, such as `<style>` or `<link rel="stylesheet">`.
316+
Shadow DOM puede incluir estilos, como `<style>` o `<link rel="stylesheet">`.
317317
318-
Local styles can affect:
318+
Los estilos locales pueden afectar:
319319
- shadow tree,
320-
- shadow host with `:host`-family pseudoclasses,
321-
- slotted elements (coming from light DOM), `::slotted(selector)` allows to select slotted elements themselves, but not their children.
320+
- shadow host con `:host`-familia de pseudoclases,
321+
- elementos eslotados (provenientes de light DOM), `::slotted(selector)` permite seleccionar elementos eslotados, pero no a sus hijos.
322322
323-
Document styles can affect:
324-
- shadow host (as it lives in the outer document)
325-
- slotted elements and their contents (as that's also in the outer document)
323+
Los estilos de documentos pueden afectar:
324+
- shadow host (ya que vive en el documento exterior)
325+
- elementos eslotados y su contenido (ya que eso también está en el documento exterior)
326326
327-
When CSS properties conflict, normally document styles have precedence, unless the property is labelled as `!important`. Then local styles have precedence.
327+
Cuando las propiedades CSS entran en conflicto, normalmente los estilos del documento tienen prioridad, a menos que la propiedad esté etiquetada como `!important`. Entonces, los estilos locales tienen prioridad.
328328
329-
CSS custom properties pierce through shadow DOM. They are used as "hooks" to style the component:
329+
Las propiedades CSS personalizadas atraviesan el shadow DOM. Se utilizan como "hooks" para aplicar estilos al componente:
330330
331-
1. The component uses a custom CSS property to style key elements, such as `var(--component-name-title, <default value>)`.
332-
2. Component author publishes these properties for developers, they are same important as other public component methods.
333-
3. When a developer wants to style a title, they assign `--component-name-title` CSS property for the shadow host or above.
334-
4. Profit!
331+
1. El componente utiliza una propiedad CSS personalizada para aplicar estilos a elementos clave, como `var(--component-name-title, <default value>)`.
332+
2. El autor del componente publica estas propiedades para los desarrolladores, son tan importantes como otros métodos de componentes públicos.
333+
3. Cuando un desarrollador desea aplicar un estilo a un título, asigna la propiedad CSS `--component-name-title` para el shadow host o superior.
334+
4. ¡Beneficio!

0 commit comments

Comments
 (0)