将css属性应用于子元素

时间:2016-07-02 23:03:07

标签: html css css-selectors

我无法理解这堂课的行为:

.h-box > div > h2,h3,h4  {
    text-align: center;
}

对我来说,这个类应该只适用于嵌套在.h-box元素中的标题。

但实际上它也适用于直接嵌套在.h-box元素中的h4头,为什么呢?这有什么不对吗?

.h-box {
		display: flex;
		margin-bottom: 2em;
		align-items: center;
		justify-content: space-between;		
	}
	.h-box > div {
		border: solid gray 2px;
		box-shadow: 1px 1px 1px 0px lightgray;
		padding: 0.5em 1em;
	}
	.h-box > div:first-of-type {
   	        margin-right: 1em;
	}	
	.h-box > * {
		width: 50%;
	}
	.h-box > div > h2,h3,h4  {
		text-align: center;
	}
<div class="h-box">
  <h4>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
  </h4>  
</div>

<div class="h-box">		     						     
  <div>
      <h3> quis nostrud exercitation </h3>
  </div>    					
  
  <div>
    <h3> quis nostrud exercitation </h3>
  </div>

</div>

4 个答案:

答案 0 :(得分:2)

看起来应该是这样的

.h-box > div > h2, .h-box > div > h3, .h-box > div > h4  {
    text-align: center;
}

使用逗号分隔值而不是为一组选择器多次重写规则。如果没有使用逗号的能力,就必须这样做

.h-box > div > h2 {
    text-align: center;
}
.h-box > div > h3 {
    text-align: center;
}
.h-box > div > h4  {
    text-align: center;
}

答案 1 :(得分:1)

您的问题是您没有定义单个选择器,而是许多选择器。逗号分隔意味着多个选择器必须应用这些规则。也就是说,您的CSS代码等同于:

a, p, span {
   text-align: center;
}

为了将规则应用于整个div内的标题,您需要:

.h-box > div > h2, .h-box > div > h3, .h-box > div > h4  {
    text-align: center;
}

您是否听说过 CSS转发器SASS/SCSSLESS CSS是最受欢迎的,您可以采用更易读的格式实施这些规则:

/* Since you can define CSS using hierarchies, it makes more readable */
.h-box > div {
    > {
       h1, h2, h3, h4 {
           text-align: center;
       }
    }
}

答案 2 :(得分:0)

你需要这样说:

.h-box > div > h2,
.h-box > div > h3,
.h-box > div > h4 {
  text-align: center;
}

,后的任何内容都是新规则。因此,您要将规则应用于文档中的所有h3h4,无论它们出现在何处。

您的代码:

.h-box > div > h2, h3, h4 {}

类似于以下内容:

.h-box > div > h2 {}
h3 {}
h4 {}

答案 3 :(得分:0)

您写了以下内容,

.h-box > div > h2,h3,h4  {
    text-align: center;
}

浏览器将其理解为,

    .h-box > div > h2  {
        text-align: center;
    }
    h3{
        text-align: center;
    }
    h4{
        text-align: center;
}

但你真正想要的是,

 .h-box > div > h2,.h-box > div > h3,.h-box > div > h4  {
        text-align: center;
    }
相关问题