0

在做一些研究时,我在 CSS 文件中看到了以下代码:

#element1{
overflow: hidden;     
width: 880px;
height: 32px;
padding: 5px 30px;
background: #c82c74;
border-bottom: 1px solid #870843;}

#element1 #element2{ 
float: left;
width: 400px;
padding-right: 25px;
margin: 0;
padding: 0;}

如您所见,element1 的 ID 有自己的一组属性和值,然后它与 element2 一起再次使用。在相应的 HTML 文件中,以下样式是这样实现的:

<div id="element1">
<div id="element2">
</div>
</div> 

这段代码是什么意思,这里实现了什么?

4

5 回答 5

4

#element1 #element2 means it is only styling the element that has an id of element2 that is inside an element that has an id of element1

If you want to style both elements with the same style then you would need to add a comma between the elements: #element1, #element2

People would use #element1 #element2 say if they wanted to override specific styles for element2 but only if it is in element1 - for example, say element2 is on all your web pages and we have the following styles:

#element2 {width:800px;}

now if you had a particular page where you only wanted it to be 400px wide you could qualify the selector to a higher level to override that element on the certain page - so say we gave the body tag an id of element1 for that specific page, adding

#element1 #element2 {width:400px;}

would mean that element2 would be 400px for that page and then 800px on all other pages

于 2013-07-17T09:52:07.247 回答
2

That last selection you made, #element1 #element2 will tell CSS to look for a child of #element1 that has an id of #element2 but when using IDs you mostly don't need to do that because IDs are used to uniquely define an object although you may use classes for these type of selection or scoping objects.

See some CSS Tricks for Scoping.

于 2013-07-17T09:52:17.180 回答
0

这些样式#element2只有在出现在#element1.

例如,如果element1是用于主页和element2搜索框的 ID,则主页上的搜索框将使用这些样式,但其他地方的搜索框不会(例如在带有 的页面上<body id="contentpage">)。

于 2013-07-17T09:55:07.410 回答
0

在你的例子中,如果你写#element2而不是#element1 #element2没有变化,但在我的例子中:

<div class="class_one">
<div class="class_two"></div>
</div>
<div class="class_two"></div>

CSS 示例 1 - 您将看到 3 个正方形 http://jsfiddle.net/BCq9C/

.class_one {
background: red;
padding: 10px;
width: 30px;
height: 30px;
}

.class_two {
background: blue;
padding: 10px;
width: 30px;
height: 30px;
}

CSS 示例 2nd - 你只会看到 2 个正方形 http://jsfiddle.net/8aDTB/

.class_one {
background: red;
padding: 10px;
width: 30px;
height: 30px;
}

.class_one .class_two {
background: blue;
padding: 10px;
width: 30px;
height: 30px;
}
于 2013-07-17T09:58:26.540 回答
-1

#element1 #element2将为唯一元素#element2内的唯一元素设置样式#element1

但是由于 anid是唯一的,因此这样做完全没有用。使用#element2就足够了。

于 2013-07-17T09:58:51.377 回答