自定义 HTML 元素是否继承父 CSS 样式? [英] Do custom HTML elements inherit parent CSS styles?

查看:30
本文介绍了自定义 HTML 元素是否继承父 CSS 样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 HTML 中创建自定义元素时,子标签是否继承父标签的 CSS 样式?

When creating custom elements in HTML, does the child tag inherit the parent's CSS styles?

这是我的测试用例,来自 Chrome:

Here is my test case, from Chrome:

var h1bProto = document.registerElement ('h1-b', 
{
  prototype: Object.create (HTMLHeadingElement.prototype),
  extends: "h1"
});

当我使用新的 h1bProto 附加一个孩子时,它会生成一个带有 is="h1-b" 的 H1 标签,示例如下:

When I append a child using the new h1bProto it generates an H1 tag with is="h1-b", example below:

var node = document.body.appendChild (new hibProto());
node.textContent = "Hello";

<h1 is="h1-b">Hello</h1>

你好

这给了我父母的 CSS 样式.但是,如果我通过先创建元素然后附加节点来添加节点,则代码如下所示:

Hello

This gives me the parents CSS styles. However, if I add a node by creating the element first, then appending the node, the code looks like this:

var node = document.createElement ("h1-b");
node.textContent = "Hello";
document.body.appendChild (node);

<h1-b>Hello</h1-b>

你好

我是否遗漏了什么,或者孩子没有继承父母的 CSS 样式?如果他们不这样做,那么使用 Shadow DOM 的最佳解决方法是?

Am I missing something, or do children not inherit the parent's CSS styles? If they don't, then is the best work around to use the Shadow DOM?

推荐答案

根据 W3 规范你不会发疯

尝试使用自定义的内置元素作为自主自定义元素将不起作用;也就是说,点击我?将简单地创建一个没有特殊的 HTMLElement行为.

Trying to use a customized built-in element as an autonomous custom element will not work; that is, Click me? will simply create an HTMLElement with no special behaviour.

Aka,在您的示例中,使用 制作标签不会应用

标签的样式或行为.相反,您必须创建一个 <h1> 标记,并将 is 属性设置为您的自定义元素的名称.我在规范中链接你的部分实际上很好地解释了如何创建标签.

Aka, in your example making a tag with <h1-b> will not apply the styling or behavior of an <h1> tag. Instead you must create an <h1> tag with the is attribute set to the name of your custom element. The section I linked you to in the spec actually does a great job explaining how to go about creating the tag.

总而言之,你只需要像这样制作你的元素:

All in all, you just need to make your element like so:

document.createElement("h1", { is: "h1-b" });

我想到的一个原因是大多数机器人不会解析您的 javascript.因此,他们将很难弄清楚您的 dom 中的元素到底是什么.想象一下,如果机器人没有意识到您的 <h1-b> 元素实际上是 <h1> 元素,那么您的 seo 会损失多少!

One reason that comes to mind for this is that most bots don't parse your javascript. As a result they would have a challenge to figure out what the elements in your dom really are. Imagine how much your seo would tank if a bot didn't realize that your <h1-b> elements were really <h1> elements!

这篇关于自定义 HTML 元素是否继承父 CSS 样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆