首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解父元素和子元素- CSS

理解父元素和子元素- CSS
EN

Stack Overflow用户
提问于 2021-06-20 12:56:15
回答 1查看 39关注 0票数 0

我是个新手,只是想对parent >子元素和CSS的首选语法有一些了解。

谁能解释一下,为什么当我删除>标签时,代码适用于container-2中的h1,但是如果我把它留在那里,字体大小规则就不适用了,而是遵循container-1的字体大小规则?

代码语言:javascript
复制
.container-1 > h1 { 
    font-size: 1em; 
}

.container-2 h1 { 
    font-size: 0.8em; 
}

我有点困惑,因为container-2的父元素与容器1的父元素不同,但它仍然适用。这是供参考的html代码。

代码语言:javascript
复制
      <div class="container-1">
                <div class="content-1">
                    <!--image-->
                    <img src="images/edge of tomorrow.jpg" alt="Edge of Tomorrow" href="featured.html" class="featured-banner">
                </div>
                <!--headings-->
                <div class="content-2">
                    <h1>Edge of Tomorrow</h1>
                    <h2>Rating: 4/5</h2>
                    <p>It leaves you on the edge, wishing for a tomorrow. An epic action movie with twists and turns along the way.</p>
                    <button class="featured-button"><a href="featured.html">Read more &#8594;</a></button>
                </div>
            </div>
        </section>

        <section class="movies">
            <!--movies for screening, 2 columns by 2 rows-->
            <!--First Row-->
            <div class="container-2">
                <!--movie1-->
                <div class="col-1-3">
                    <!--movie 1 image-->
                    <img src="images/500 days of summer.jpg" alt="500 Days of Summer" href="movie1.html" class="movie-poster">
                    <h1>500 Days of Summer</h1>
                    <h2>Rating: 4/5</h2>
                    <h3>This is not a love story.</h3>
                </div>
</div>

这与特异性有关吗?应用字体规则的最佳实践是使用>子元素标记,还是不使用,即.container-1 > h1 vs .container-1 h1?

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-06-20 13:03:46

如果使用的是>,则会选择所有h1标记,这些标记是container-1的直接子标记

代码语言:javascript
复制
.container-1 > h1 { 
    font-size: 1em; 
}

但是如果你没有使用>,那么所有的h1标签都会被选中,它们是container-2的子标签(可以在任何级别)

代码语言:javascript
复制
.container-2 h1 { 
    font-size: 0.8em; 
}

在您的例子中,h1不是container-1的直接子对象。它是container-1的子级到子级(content-2)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68052782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档