You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 8-web-components/6-shadow-dom-style/article.md
+63-63Lines changed: 63 additions & 63 deletions
Original file line number
Diff line number
Diff line change
@@ -1,21 +1,21 @@
1
-
# Shadow DOM styling
1
+
# Estilo Shadow DOM
2
2
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.
4
4
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.
6
6
7
7
## :host
8
8
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).
10
10
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>`.
12
12
13
-
That's exactly what `:host`does:
13
+
Eso es exactamente lo que `:host`hace:
14
14
15
15
```html run autorun="no-epub" untrusted height=80
16
16
<templateid="tmpl">
17
17
<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*/
19
19
:host {
20
20
position: fixed;
21
21
left: 50%;
@@ -42,32 +42,32 @@ customElements.define('custom-dialog', class extends HTMLElement {
42
42
</custom-dialog>
43
43
```
44
44
45
-
## Cascading
45
+
## Cascada
46
46
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.
48
48
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.
50
50
51
-
For instance, if in the document we had:
51
+
Por ejemplo, si en el documento tenemos:
52
52
```html
53
53
<style>
54
54
custom-dialog {
55
55
padding: 0;
56
56
}
57
57
</style>
58
58
```
59
-
...Then the`<custom-dialog>`would be without padding.
59
+
...Entonces el`<custom-dialog>`estaría sin padding.
60
60
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.
62
62
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.
64
64
65
65
66
66
## :host(selector)
67
67
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`.
69
69
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`:
71
71
72
72
```html run autorun="no-epub" untrusted height=80
73
73
<templateid="tmpl">
@@ -101,40 +101,40 @@ customElements.define('custom-dialog', class extends HTMLElement {
101
101
102
102
103
103
<custom-dialogcentered>
104
-
Centered!
104
+
¡Centrado!
105
105
</custom-dialog>
106
106
107
107
<custom-dialog>
108
-
Not centered.
108
+
No centrado.
109
109
</custom-dialog>
110
110
```
111
111
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>`.
113
113
114
114
## :host-context(selector)
115
115
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`.
117
117
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:
119
119
120
120
```html
121
121
<bodyclass="dark-theme">
122
122
<!--
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
124
124
-->
125
125
<custom-dialog>...</custom-dialog>
126
126
</body>
127
127
```
128
128
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.
130
130
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)
132
132
133
-
Now let's consider the situation with slots.
133
+
Ahora consideremos la situación con los slots.
134
134
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.
136
136
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:
138
138
```html run autorun="no-epub" untrusted height=80
139
139
<style>
140
140
*!*
@@ -163,11 +163,11 @@ customElements.define('user-card', class extends HTMLElement {
163
163
</script>
164
164
```
165
165
166
-
The result is bold, but not red.
166
+
El resultado es bold, pero no red.
167
167
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.
169
169
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:
171
171
172
172
```html run autorun="no-epub" untrusted height=80
173
173
<user-card>
@@ -191,14 +191,14 @@ customElements.define('user-card', class extends HTMLElement {
191
191
</script>
192
192
```
193
193
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.
195
195
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.
197
197
198
-
1. That'sa 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 dellight DOM. El nombre delslot no importa. Cualquier elemento eslotado, pero solo el elemento en si, no sus hijos.
199
+
2. El elemento coincide con el `selector`.
200
200
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:
202
202
203
203
```html run autorun="no-epub" untrusted height=80
204
204
<user-card>
@@ -224,54 +224,54 @@ customElements.define('user-card', class extends HTMLElement {
224
224
</script>
225
225
```
226
226
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:
228
228
229
229
```css
230
230
::slotted(divspan) {
231
-
/*our slotted <div> does not match this*/
231
+
/*nuestro slotted <div> no coincide con esto*/
232
232
}
233
233
234
234
::slotted(div) p {
235
-
/*can't go inside light DOM */
235
+
/*No puede entrar en light DOM */
236
236
}
237
237
```
238
238
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`.
240
240
241
-
## CSS hooks with custom properties
241
+
## CSS hooks con propiedades personalizadas
242
242
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?
244
244
245
-
Selectors like `:host` apply rules to `<custom-dialog>` element or `<user-card>`, but how to styleshadow DOM elements inside them?
245
+
Selectores como `:host` aplican reglas al elemento `<custom-dialog>` o `<user-card>`, ¿pero cómo aplicar estilos a elementos delshadow DOM dentro de ellos?
246
246
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 delshadow DOM del documento. Pero así como exponemos métodos para interactuar con nuestro componente, podemos exponer variables CSS (propiedades CSS personalizadas) para darle estilo.
248
248
249
-
**Custom CSS properties exist on all levels, both in light andshadow.**
249
+
**Existen propiedades CSS personalizadas en todos los niveles, tanto en light comoshadow.**
250
250
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:
252
252
253
253
```html
254
254
<style>
255
255
.field {
256
256
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*/
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>`:
265
265
266
266
```css
267
267
user-card {
268
268
--user-card-field-color: green;
269
269
}
270
270
```
271
271
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.
273
273
274
-
Here's the full example:
274
+
Aquí está el ejemplo completo:
275
275
276
276
```html run autorun="no-epub" untrusted height=80
277
277
<style>
@@ -311,24 +311,24 @@ customElements.define('user-card', class extends HTMLElement {
311
311
312
312
313
313
314
-
## Summary
314
+
## Resumen
315
315
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">`.
317
317
318
-
Local styles can affect:
318
+
Los estilos locales pueden afectar:
319
319
- 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.
322
322
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)
326
326
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.
328
328
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:
330
330
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 styleatitle, 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.
0 commit comments