📜  解释 CSS 中的嵌套和分组

📅  最后修改于: 2022-05-13 01:56:36.283000             🧑  作者: Mango

解释 CSS 中的嵌套和分组

嵌套和分组概念对于 Web 开发人员编写精确代码非常重要。您可以对项目进行分组和嵌套以减少编写的代码量,这将减少代码的长度并让页面加载得更快。这是一种简化代码的方法。在嵌套和分组的帮助下,我们可以在代码中更加具体。在本文中,我们将看到嵌套和分组如何帮助优化代码并使其高效并提高可读性。

嵌套: CSS 中的嵌套属性有助于将一个样式规则嵌套在另一个样式规则中,子规则的选择器相对于父规则的选择器。它有助于提高 CSS 样式表的模块化和可维护性,从而提高代码的整体可读性。例如,如果您编写一个结构化的 CSS 模块,而不是为每个 HTML 元素指定单独的选择器,即使用许多类或 ID 选择器,您可以简单地为其他选择器中的选择器指定属性。在嵌套 CSS 属性时,HTML 元素形成树状结构。嵌套是为特定属性的多个选择器创建 CSS 规则的快捷方式。因此,我们可以简单地将选择器嵌套在其他选择器中,而不是为不同的选择器重写相同的属性集。出于这个原因,我们不仅减少了代码的大小,而且还减少了整体加载时间。

句法:

class1_selector class2_selector id_selector  {
  property: value;
}

例子:

table tr th {
  background-color: beige;
}

方法:

  • 选择 id/class 选择器并添加一个空格以将一个与另一个分开。
  • 添加元素的样式属性。

注意:具体嵌套顺序。

示例:在此示例中,我们将 标记嵌套在

标记内,将 标记嵌套在 标记内。

HTML


  

    

  

  
    

        This is a         link         within a paragraph element.     

                                                                                                                                                                                            
NameAge
Ram50
Rahul65
Vikram26
  


HTML


  

    

  

    

GeeksForGeeks

    

Smaller heading!

       

This is                      anchor tag              

       

This is a paragraph.

  


输出:我们使用嵌套得到了绿色的 标记和米色的 标记。

分组:分组用于将多个元素一起选择以将公共样式属性应用于它们。出于这个原因,它有助于减少具有多个具有相同属性的选择器的代码的长度。这使代码易于阅读。使用分组时,页面加载时间和代码开发时间也会减少。

无需编写这么长的代码,而是为不同的选择器指定相同的属性:

我们可以将它们分组并像这样写,我们需要逗号( )来分组各种选择器。

方法:

输出:

具有相同属性的分组选择器

嵌套和分组的区别:

S.No.

Nesting

Grouping

1.

Nesting property facilitates nesting one style rule inside another, with the selector of the child rule that is relative to the selector of the parent rule.

Grouping property provides the same properties with values to a number of selectors at a time.

2.

It may help to simplify & manage the properties for the different elements at a time but It may be complicated if the number of nesting elements that contain the same properties, is increased. It may be difficult to manage such a nesting property.

It is simple to apply the properties to the number of different elements at a time & can be managed easily. 

3.

In this case, if we need to modify the property for any specific element ie, either the parent element or child element in CSS, we need to change it manually for that specific element, if it is in nesting. For large-size code, it may be an inefficient way to manage the CSS properties.

There are no restrictions as such in the grouping.