Antoine BERNIER
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: ironhack, lecture, --- <style> .markdown-body img[src$=".png"] {background-color:transparent;} .alert-info.lecture, .alert-success.lecture, .alert-warning.lecture, .alert-danger.lecture { box-shadow:0 0 0 .5em rgba(64, 96, 85, 0.4); margin-top:20px;margin-bottom:20px; position:relative; ddisplay:none; } .alert-info.lecture:before, .alert-success.lecture:before, .alert-warning.lecture:before, .alert-danger.lecture:before { content:"👨‍🏫\A"; white-space:pre-line; display:block;margin-bottom:.5em; /*position:absolute; right:0; top:0; margin:3px;margin-right:7px;*/ } b { --color:yellow; font-weight:500; background:var(--color); box-shadow:0 0 0 .35em var(--color),0 0 0 .35em; } .skip { opacity:.4; } </style> ![](https://i.imgur.com/1QgrNNw.png) # CSS | Advanced Selectors ## Learning Goals After this lesson, you will be able to: - Select elements using basic selectors - Select elements combining different selectors - Select elements based on their relationship to other elements - Select elements based on their attributes ## Combining CSS Selectors Before learning about combined CSS selectors, it's a good idea to understand the document tree in the [Document Object Model](https://en.wikipedia.org/wiki/Document_Object_Model). If you understand the document tree concept, then CSS selectors will be much easier to understand and therefore apply. All <b>HTML documents can be represented as trees</b>. Each level of the tree is described in the same manner as a human family tree, with ancestors, descendants, parents, children and siblings. CSS selectors can describe elements in the document tree. :::info lecture ![](https://i.imgur.com/P2riZwi.png) ::: :::info lecture Expliquer le vocabulaire : - ancêtre/déscendant : quelque soit le niveau - parent/enfant : direct ::: For example, in any HTML document, the `<body>` element is the <b>==ancestor==</b> of all other elements shown on the page. On the contrary, a <b>==descendant==</b> refers to any element that is connected but lower down the document tree - no matter how many levels lower. Parents and children work the same. A <b>==parent==</b> is an element that is directly above and connected to an element in the document tree; a <b>==child==</b> is directly below and connected to an element in the document tree. ```html <ul> <li class="menu-item"></li> <li class="menu-item"></li> </ul> ``` In this example, the `<ul>` is a parent to every `<li>` . Those `<li>` elements are its children. ## Selecting Descendants ### Direct Descendants (Children) :::info lecture "L'enfant direct de..." ::: :::info ```css parent > child { property: value; } ``` ::: The [<b>></b> combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors) separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first. Imagine you have several lists and you want to style them all. All *li* tags inside the menu *ul* tag will have 50px height and 100px width. One option would be to assign a class to every `li` tag in the menu list, then write the properties for them. ```html <ul> <li class="menu-item"></li> <li class="menu-item"></li> <li class="menu-item"></li> <li class="menu-item"></li> <li class="menu-item"></li> </ul> ``` ```css .menu-item { width: 100px; height: 50px; } ``` But.. we have an easier way: [The child selector](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors)! The `> combinator` will select those elements matched by the second selector that are direct children of elements matched by the first. If we add a `menu` id to the `ul`, we can simply select all of its `li` children by using the `#menu > li` selector: ```html <ul id="menu"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> ``` ```css #menu > li { width: 100px; height: 50px; } ``` Now we have a rule saying that <b>every `li` child of the element with `menu` id</b> will have that width and height. ### Descendant Selector :::info lecture "Un déscendant de..." (quelque soit le niveau) ::: :::info ```css selector1 selector2 { property: value; } ``` ::: The [<b>` `</b> Descendant Selector](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_selectors) matches those elements **matched by the second selector**, but only those, which **have an ancestor element, matched by the first selector**. --- Let's take this HTML fragment for a second and think about how we would target the `em` inside the `li`, without targeting the `em` inside the `p`: ```htmlmixed <p>Ironhack <em>Descendant</em> Selectors</p> <ul> <li>item 1</li> <li>item 2</li> <li><em>item 3</em></li> </ul> ``` :::info lecture On ne veut ici styliser QUE le `<em>` de la liste. ::: Well, we could of course add a class to the second `em`, or we could add an ID as well. However, using this combination of selectors helps us match elements without having to mess around with the HTML too much. ![](https://i.imgur.com/YdqDUNh.png) One of the goals of this course is to teach you to keep the HTML as tidy, clean, and compact as possible. These selectors will help you target elements without having to add classes everywhere: :::info lecture Test dans codepen du sélecteur `ul em`: ::: <iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/amBQkV/?height=265&theme-id=light&default-tab=html,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/amBQkV/'>amBQkV</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>. </iframe> :::warning :zap: Remember to click **Edit on CodePen** so you can code along and play around ::: Here, the rule that we wrote <b>`ul em`</b> will apply to all `em` elements that are descendants of an `ul`. Therefore, the first `em` inside the `p` will not be affected. Useful right? ## Selecting Siblings ### Adjacent Sibling :::info lecture "Le frère tout de suite après" ou "celui tout de suite à coté" ::: :::info ```css formerElement + targetElement { property: value; } ``` ::: This is referred to as an [adjacent selector](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors) or next-sibling selector. It will select only the specified element that immediately follows the former specified element This selector allows you to get the elements that are next to each other: --- :::info lecture En jaune, la `<div>` tout de suite après `#former`: ```css #former + div ``` ::: <iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/amBQEG/?height=265&theme-id=light&default-tab=html,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='https://codepen.io/ironhack/pen/amBQEG/'>Example</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>. </iframe> If we look carefully at the CSS code: ```css /* All DIVs Green by default */ div { background-color: green;} /* ID=former... make it red*/ #former { background-color: red; } /* First adjacent sibling of #former is YELLOW */ #former + div { background-color: yellow; } ``` ## Multiple selection :::info lecture La virgule ::: :::info ```css selector1, selector2 { property: value; } ``` ::: Imagine we want all our titles `h1`-`h6` to be colored blue. We can add a separate rule for `h1`, another rule for `h2`, another for `h3`... but there is a better way. The multiple selections allow us to apply the same list of rules to different elements: ```css h1, h2 { color: blue; } ``` And this method can work with more complicated selectors as well, although you should probably put each selector in a different line for ease of reading. For example, we may want different elements to have background-color yellow: ```css .todo-list > li, h2 + .red-box, h2 { background-color: yellow; } ``` :::info lecture On peut sauter des lignes entre les sélecteurs pour + de lisibilité. ::: You can mix selectors as much as you need to create awesome and beautiful web pages! ## Attribute Selector :::info lecture "l'élément portant l'attribut..."" ::: :::info ```css element[attr-name="value"] { property: value; } ``` ::: We can select elements by tag name, why not select an element by it's attributes? Let's see how this works: <iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/GjAWAo/?height=265&theme-id=light&default-tab=html,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/GjAWAo/'>GjAWAo</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>. </iframe> Only the links with the word `hack` in their `src` attribute are affected by the rule, and therefore are show in green. :::info lecture Spec : https://www.w3.org/TR/selectors-3/#attribute-selectors ::: Another examples of this same selector: | Selector | What does it select? |----------------------|--------------------------------------------------------------- | `[attribute]` | All elements with the specified attribute | `[attribute=value]` | All elements where the specified attribute is <b>equal to</b> ‘value’ | `[attribute~=value]` | All elements with an attribute which has a list of whitespace-separated values, one of which is exactly equal to ‘value’ | `[attribute|=value]` | All elements with an attribute which has a hyphen-separated list of values beginning (from the left) with ‘value’ | `[attribute^=value]` | All elements with an attribute <b>beginning with</b> ‘value’ | `[attribute$=value]` | All elements with an attribute <b>ending with</b> ‘value’ | `[attribute*=value]` | All elements with an attribute containing the substring ‘value’ Here you have one more example to play around: <iframe height="485" style="width: 100%;" scrolling="no" title="attr-selectors-css" src="https://codepen.io/abernier/embed/NWKmera?height=485&theme-id=0&default-tab=html,result" frameborder="no" allowtransparency="true" allowfullscreen="true"> See the Pen <a href='https://codepen.io/abernier/pen/NWKmera'>attr-selectors-css</a> by Antoine BERNIER (<a href='https://codepen.io/abernier'>@abernier</a>) on <a href='https://codepen.io'>CodePen</a>. </iframe> ## Summary :::info lecture ![](https://i.imgur.com/ByNZN2K.png) ::: In this Unit, we have learnt: - How to select descendants `selector1 selector2` and children `selector1 > select2` of a node - How to select siblings `selector1 + selector2` of a node - How to combine selector rules `selector1, selector2` - How to select elements based on their attribute values `element[attr="value"]` ## Extra Resources - [Css-tricks](https://css-tricks.com/attribute-selectors/) | Interesting article explaining further uses of attribute selectors in the real world. - [CSS Selectors](http://www.w3schools.com/cssref/css_selectors.asp) | All selectors available

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully