据我所知,没有可靠的方法来完成我的目标,但我想我还是会请教这里的专家,看看是否可以完成。
我正在寻求创建一种简化的样式设置方法,允许某人使用带有采用嵌套标签格式的类或 ID 的单个标签。例如,一个 DIV 看起来内部有另一个 DIV,允许使用目前只能通过使用嵌套元素实现的更复杂的样式。
我想做的一个例子是:
<div class="nesteddiv">{content}</div>
并使其呈现为:
<div class="outerdiv"><div class="innerdiv">{content}</div></div>
目标可能是让 outerdiv 和 innerdiv 拥有自己的边框、背景、边距和间距,以创建无法在单个 DIV 上完成的复杂样式(我认为单个 DIV 不可能实现DIV 有多个边框)
我知道::before 和::after 中有伪元素,允许您在内容前后的包含元素中插入原始文本或图像,但这些不能插入 html 标记并让它们呈现。有没有另一种方法可以将单个 html 元素转换为呈现为多个嵌套元素的东西?我试图避免使用 Javascript,因为我的一些观众禁用了 Javascript。我知道有一种方法可以在 Javascript 中创建自定义元素,也可以用更复杂的嵌套代码简单地用某个类替换所有 DIV,但如果纯 HTML 中已经有更简单的方法,我宁愿避免所有这些额外的编码/CSS。
最佳答案
没有什么好的方法可以做到这一点。
您可以在元素上使用display: table
。假设内容不是表格元素,table-row
和 table-cell
anonymous elements将被创建:
Generate missing child wrappers:
- If a child C of a 'table' or 'inline-table' box is not a proper table child, then generate an anonymous 'table-row' box around C and all consecutive siblings of C that are not proper table children.
- If a child C of a 'table-row' box is not a 'table-cell', then generate an anonymous 'table-cell' box around C and all consecutive siblings of C that are not 'table-cell' boxes.
但是,问题是您不能使用 CSS 选择器来选择那些匿名元素。所以你不能设计它们。因此,这种方法通常是无用的。
另一种方法相反:生成所需元素的伪元素包装器。这可以通过 Generated and Replaced Content Module 提出的 ::outside
来完成。 :
An '::outside' pseudo-element is one that is generated immediately outside the pseudo-element's superior.
When given a parameter, '::outside(n)' represents an nth pseudo-element generated immediately around the n-1th pseudo-element.
For example, the following rules:
div { display: block; border: dashed; } div::outside { display: block; border: dashed; } div::outside(2) { display: block; border: dashed; }
...would result in the following rendering objects:
,-----------------------. <-- border of ::outside(2) | ,-------------------. | <-- border of ::outside | | ,---------------. | | <-- border of DIV | | | DIV | | | | | `---------------' | | | `-------------------' | `-----------------------'
但是,这个模块是一个草案,自 2003 年以来就没有更新过,我认为它从未被实现过。
几个月前,我向 CSS WG 发送了一封电子邮件,建议使用 ::contents
伪元素来生成内容的包装器(不包括 ::before
也不是 ::after
)。这个伪元素默认有 display: contents
,因此除非你改变 display
,否则它不会被注意到。电子邮件被忽略。
但我希望将来有某种方法可以实现这一目标。能够使用 display: contents
“展开”内容但不能将内容包装在容器中是没有意义的。
关于HTML5/CSS3 : Any way to use pseudo elements to create a tag within a tag?(避免使用 Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34711744/