首页 > 解决方案 > 在 html 页面中有多个主要元素的替代方法是什么?

问题描述

我的 HTML 代码一次包含几个主要元素。这些主要元素也受到一些 CSS 样式表的影响,这些样式表给它们一个边框。

<html>
<head>
<style>
<!-- Here come css which give `main` elements a nice border. -->
<!-- This is a MWE, other attributes may follow. -->
    main { border-style: solid; }
</style>
</head>
<body>
<main>
<p>Some text</p>
</main>
<main>
<p>Some more text</p>
</main>
<main>
<p>And another section with some text</p>
</main>
</body>
</html> 

这在我测试过的浏览器上运行良好。但我也知道多个mains不符合标准。

什么是避免main上述多个元素但在每个浏览器上给出完全相同的行为的最佳实践,无论我在 CSS 样式表中添加了什么?

标签: htmlcss

解决方案


分配您的元素名称或 ID,以便在 css 中您可以区分哪个元素应该显示哪些样式。这是一个例子:

<! -- this would be your element in the body -->
<div id="mainStyle></div>

并且在样式表中,对应于该 id 的样式应该是

#mainStyle {

     //attributes defined here

}

任何没有相同 id 的元素都不会受到影响


推荐阅读