英文:
Is there a way to style a specific element inside a div but not affect all elements in general?
问题
Sample code
<head>
<title>Albert</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1> Hello</h1>
<div class="">
<h1> I'm Albert</h1>
<p> a physicist</p>
</div>
</body>
I want to be able to write in the css/styles.css
something like
div{
background-color: #E4F9F5;
h1 {
margin-top:0;
margin-bottom:0px;
margin-left: 0px;
margin-right: 0px;
}
}
Of course, the above does not work.
My question: Is it possible to define select a specific element inside a div so that only that element inside of the div is changed and not every element is changed?
英文:
Sample code
<head>
<title>Albert</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1> Hello</h1>
<div class="">
<h1> I'm Albert</h1>
<p> a physicist</p>
</div>
</body>
I want to be able to write in the css/styles.css
something like
div{
background-color: #E4F9F5;
h1 {
margin-top:0;
margin-bottom:0px;
margin-left: 0px;
margin-right: 0px;
}
}
Of course, the above does not work.
My question: Is it possible to define select a specific element inside a div so that only that element inside of the div is changed and not every element is changed?
答案1
得分: 4
你的CSS结构还不正确。像SASS这样的工具可以使用你尝试的语法来生成可供浏览器使用的CSS。在普通的CSS中,你需要使用特定的选择器,而不是嵌套样式规则。例如,要选择作为<div>
元素的直接子元素的<h1>
元素:
div {
background-color: #E4F9F5;
}
div > h1 {
background-color: green;
}
或者,要选择作为任何<div>
的后代的任何<h1>
:
div {
background-color: #E4F9F5;
}
div h1 {
background-color: green;
}
有各种各样的选项。总体来说,重点是CSS结构不是嵌套在语法中,而是作为一个具有更有针对性的选择器的单独样式规则。
英文:
You're close, the CSS structure just isn't correct. Tools like SASS can do this with the syntax you're attempting and then output CSS to be used by the browser. In plain CSS you'd use a specific selector instead of nesting the style rules. For example, to target <h1>
elements as a direct child of <div>
elements:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
div {
background-color: #E4F9F5;
}
div > h1 {
background-color: green;
}
<!-- language: lang-html -->
<h1>Hello</h1>
<div>
<h1>I'm Albert</h1>
<p>a physicist</p>
</div>
<!-- end snippet -->
Or perhaps to target any <h1>
that's a descendant of any <div>
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
div {
background-color: #E4F9F5;
}
div h1 {
background-color: green;
}
<!-- language: lang-html -->
<h1>Hello</h1>
<div>
<span><h1>I'm Albert</h1></span>
<p>a physicist</p>
</div>
<!-- end snippet -->
There are a variety of options available. The overall point is that the structure isn't nested in the CSS syntax, instead its a separate style rule with a more targeted selector.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论