How to define styles according to the contextual relationship of elements in CSS
Editor to share with you how to define styles according to the contextual relationship of elements in CSS. I hope you will get something after reading this article. Let's discuss it together.
CSS id selector
The id selector can specify a specific style for HTML elements marked with a specific id.
The id selector is defined by "#".
The id attribute can only appear once in each HTML document.
Example
# red {color:red;} # green {color:green;}
Note: of the two id selectors above, the first defines the element with a red color and the second defines the element with a green color.
This paragraph is red.
This paragraph is green.
Note: the p element whose id attribute is red is shown in red, while the p element whose id attribute is green is shown in green.
Tip: the id attribute can only appear once in each HTML document and is the only identifier (such as: JS gets page elements).
Id selector and derived selector
In modern layouts, id selectors are often used to build derived selectors.
Elements marked as sidebar can only appear once in the document, but this id selector can be used multiple times as a derived selector.
Example
# sidebar p {font-style: italic; text-align: right; margin-top: 0.5em;} # sidebar h3 {font-size: 1em; font-weight: normal; font-style: italic; margin: 0; line-height: 1.5; text-align: right;}
Hint: both the p element and the h3 element within the element where id is sidebar have been specially treated.
Separate selector
The id selector works independently, even if it is not used to create a derived selector:
# sidebar {border: 1px dotted # 000; padding: 10px;}
Tip: elements whose id is sidebar will have the black dotted border of 1px and the inner margin of 10px (padding).
Note: older Windows/IE browsers may ignore this rule unless you specifically define the element to which this selector belongs:
Div#sidebar {border: 1px dotted # 000; padding: 10px;} after reading this article, I believe you have a certain understanding of "how to define styles according to the contextual relationship of elements in CSS". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!