{"resource":{"author":{"id":"h2so9H8jPMmgUKGghoNl","name":"Yomesh Gupta","username":"yomeshgupta"},"content":{"link":null,"difficulty":1,"domain":2,"type":1,"isInternal":true,"body":"The `:nth-child()` CSS pseudo-class matches elements based on their position among a group of siblings i.e. let us say a div has five children where 3 are `p` tags and 2 are `span` tags. If we write the following HTML and CSS --\r\n\r\n```html\r\n<div>\r\n  <p>One</p>\r\n  <span>Two</span>\r\n  <p>Three</p>\r\n  <p>Four</p>\r\n  <span>Five</span>\r\n</div>\r\n```\r\n\r\n```css\r\ndiv {\r\n  background: black;\r\n  color: white;\r\n}\r\n\r\ndiv p:nth-child(2n+1) {\r\n  color: red;\r\n}\r\n```\r\n\r\nIt highlights `One` and `Three` only. \r\n\r\n![Output 1](https://ik.imagekit.io/devtoolstech/blog/nth-child/Screenshot_2023-02-17_at_11.55.38_PM_bguuSDkek.png?ik-sdk-version=javascript-1.4.3&updatedAt=1676659138066)\r\n\r\n## Now, why is that?\r\n\r\nFor this, you need to mainly understand the functional notation syntax of the `:nth-child` selector i.e. `:nth-child(An+B)`. Here\r\n\r\n- `A` is the step size\r\n- `B` is the offset\r\n- `n` is the non-negative integer, starting from `0`.\r\n\r\nIn our example, `:nth-child(2n+1)` where `A=2`, `B=1`, and `n can go from 0,1,2..` to `Infinity`.\r\n\r\n```\r\n:nth-child(2(0)+1) => :nth-child(0 + 1) => :nth-child(1)\r\n:nth-child(2(1)+1) => :nth-child(2 + 1) => :nth-child(3)\r\n:nth-child(2(2)+1) => :nth-child(4 + 1) => :nth-child(5)\r\n...\r\n```\r\n\r\n## Element Indexing\r\n\r\nIn our CS classes or our dev work, we are used to having 0-based indices. However, in the case of counting the elements, 1-based indexing is used i.e.\r\n\r\n```html\r\n<div>\r\n  <p>One</p> // 1\r\n  <span>Two</span> // 2\r\n  <p>Three</p> // 3\r\n  <p>Four</p> // 4\r\n  <span>Five</span> // 5\r\n</div>\r\n```\r\n\r\n**The `n` starts from `0` but elements counting starts from `1`.** Hence, it matches element `One` and `Three`.\r\n\r\n## Why is Five not highlighted in red?\r\n\r\nFor `:nth-child` selector, the child count includes children of any element type; but it is considered a match only if the element at that child position is of the specified element type. Hence, even though `:nth-child(2n+1)` produces `5` when `n=2` and we have a fifth element, it is highlighted because it is of type `span`. Our condition to match the element must be at the right position and right type.\r\n\r\nIf we change the fifth element to type `p` then it would be highlighted.\r\n\r\n```html\r\n<div>\r\n  <p>One</p> // 1\r\n  <span>Two</span> // 2\r\n  <p>Three</p> // 3\r\n  <p>Four</p> // 4\r\n  <p>Five</p> // 5\r\n</div>\r\n```\r\n\r\n![Output 2](https://ik.imagekit.io/devtoolstech/blog/nth-child/Screenshot_2023-02-17_at_11.55.52_PM_99EUwTpyA.png?ik-sdk-version=javascript-1.4.3&updatedAt=1676659220767)\r\n\r\n## Learn by examples\r\n","languages":["react"],"editorConfig":{"react":{"nodes":[{"nodeId":"4aad7d47-c5b9-4d0c-9b0c-c0a4340e87ec","nodeType":"file","nodeName":"App.js","nodeContent":"import styled from 'styled-components';\n\nconst Container = styled.div`\n  &:hover {\n    ul[data-key='${(props) => props.label}'] > ${(props) => props.label} {\n      background-color: yellow;\n    }\n\n    p {\n      display: block;\n    }\n  }\n`;\n\nconst items = [\n  {\n    id: 1,\n    label: ':first-child',\n    description: 'Highlighting the first child.',\n  },\n  {\n    id: 2,\n    label: ':last-child',\n    description: 'Highlighting the last child.',\n  },\n  {\n    id: 3,\n    label: ':nth-child(2)',\n    description: 'Highlighting the second child.',\n  },\n  {\n    id: 4,\n    label: ':nth-last-child(2)',\n    description: 'Highlighting the second child from the last.',\n  },\n  {\n    id: 5,\n    label: ':nth-child(odd)',\n    description:\n      'Highlighting the every odd child i.e. 1,3,5,7,9....and so on.',\n  },\n  {\n    id: 6,\n    label: ':nth-child(even)',\n    description:\n      'Highlighting the every odd child i.e. 2,4,6,8,10....and so on.',\n  },\n  {\n    id: 7,\n    label: ':nth-child(n+4)',\n    description:\n      'Highlighting the every child starting from 4 i.e. 4,5,6,7....and so on.',\n  },\n  {\n    id: 8,\n    label: ':nth-child(3n-1)',\n    description:\n      'Highlighting the every matching the condition i.e. (3(1) - 1) = 2, (3(2) - 1) = 5',\n  },\n  {\n    id: 9,\n    label: ':nth-child(3n+1)',\n    description:\n      'Highlighting the every matching the condition i.e. (3(0) + 1) = 1, (3(1) + 1) = 4, (3(2) + 1) = 7',\n  },\n  {\n    id: 10,\n    label: ':nth-child(4n)',\n    description:\n      'Highlighting the every matching the condition i.e. (4(1)) = 4',\n  },\n];\n\nexport default function App() {\n  return (\n    <main>\n      {items.map((item) => {\n        return (\n          <Container label={item.label} key={item.id} className=\"content\">\n            <div>\n              <span>{item.label}</span>\n              <ul data-key={item.label}>\n                <li></li>\n                <li></li>\n                <li></li>\n                <li></li>\n                <li></li>\n                <li></li>\n              </ul>\n            </div>\n            {item.description ? <p>{item.description}</p> : null}\n          </Container>\n        );\n      })}\n    </main>\n  );\n}\n","nodeLanguage":"javascript"},{"nodeId":"f7578692-c62f-4c69-8c17-4876fd36eff1","nodeType":"file","nodeName":"index.js","nodeContent":"import { StrictMode } from \"react\";\nimport ReactDOM from \"react-dom\";\n\nimport App from \"./App\";\nimport \"./style.css\"; \n\nconst rootElement = document.getElementById(\"root\");\nReactDOM.render(\n  <StrictMode>\n    <App />\n  </StrictMode>,\nrootElement\n);","nodeLanguage":"javascript"},{"nodeId":"3f480fbb-5d4a-4a3a-9e30-80af7d530e96","nodeType":"file","nodeName":"style.css","nodeContent":"* {\n  box-sizing: border-box;\n  margin: 0;\n  padding: 0;\n}\n\nbody {\n  font-family: sans-serif;\n  -webkit-font-smoothing: auto;\n  -moz-font-smoothing: auto;\n  -moz-osx-font-smoothing: grayscale;\n  font-smoothing: auto;\n  text-rendering: optimizeLegibility;\n  font-smooth: always;\n  -webkit-tap-highlight-color: transparent;\n  -webkit-touch-callout: none;\n  background: #2f3542;\n}\n\nmain {\n  width: 80%;\n  margin: 50px auto;\n  padding: 20px;\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n  align-items: center;\n  border: 1px solid #ecf0f1;\n  transition: all 0.2s ease-in-out;\n  color: white;\n}\n\n.content {\n  width: 100%;\n  padding: 10px;\n  border-radius: 4px;\n  transition: all 0.2s ease-in-out;\n  cursor: pointer;\n}\n\n.content div {\n  display: flex;\n  justify-content: space-between;\n}\n\n.content div span {\n  font-weight: 600;\n}\n\n.content p {\n  padding: 10px 0px 0px 0px;\n  color: #ebebeb;\n  font-size: 14px;\n  display: none;\n}\n\n.content ul {\n  display: flex;\n  justify-content: space-between;\n  gap: 20px;\n}\n\n.content ul li {\n  width: 20px;\n  height: 20px;\n  border-radius: 50%;\n  background-color: rgba(255, 255, 255, 0.7);\n  list-style: none;\n}\n\n.content:hover {\n  background-color: #000000;\n}\n","nodeLanguage":"css"},{"nodeId":"93f9d0ad-b85e-483e-91cb-0b8d4c8353c4","nodeType":"file","nodeName":"index.html","nodeContent":"<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Document</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n  </body>\n</html>","nodeLanguage":"html"}],"dependencies":{"react":"17.0.2","react-dom":"17.0.2","react-scripts":"4.0.0","styled-components":"5.3.6"},"openPaths":["/App.js","/index.js","/index.html","/style.css"],"entry":"App.js","activePath":"/style.css"}}},"stats":{"views":14327,"used":0,"likes":0},"description":"","published":true,"isActive":true,"tags":["javascript","frontend","code","programming","ui","ux","interactive examples","codedamn","nth-child selectors","pseudo selectors","css selectors","sass","scss","less","styling","html","css fundamentals","frontend fundamentals","examples","codesandbox"],"slug":"understanding-nth-child-selectors-in-css---rid---ZD7WRQQ8iSNv8SCSZdTG","isPremium":false,"categories":[],"requires":[],"_id":"63f077e9412456738aaee88c","title":"Understanding Nth-Child Selectors in CSS","resourceId":"ZD7WRQQ8iSNv8SCSZdTG","createdAt":1676703721912,"modifiedAt":1676704374212},"currentUser":null,"isOwner":false,"recommendations":{"questions":[{"_id":"643901a96577005718b96916","content":{"languages":["javascript","typescript"],"difficulty":2},"tags":["javascript","problem solving","lodash","ui","ux","javascript interview question","coding","programming","sorting","array sort"],"slug":"how-to-sort-an-array-of-objects-by-property-values-or-frontend-problem-solving-or-javascript-interview-questions-or-lodash-polyfill---qid---SZYi8egqRm7yPWVSY13V","title":"How to Sort an Array of Objects by Property Values? | Frontend Problem Solving | JavaScript Interview Questions | Lodash Polyfill","questionId":"SZYi8egqRm7yPWVSY13V"},{"_id":"6215e6591641361c7c65de90","content":{"difficulty":3,"languages":"javascript"},"tags":["javascript","frontend","coding","architecture","js fundamentals","web","system design"],"slug":"how-would-you-implement-pagination-in-a-frontend-application-or-javascript-interview-questions-or-frontend-architecture---qid---IL8Whw2ayeqmg0kvHQLd","title":"How would you implement pagination in a frontend application? | JavaScript Interview Questions | Frontend Architecture","questionId":"IL8Whw2ayeqmg0kvHQLd"},{"_id":"636df7cebc012474df4d37a6","content":{"languages":["javascript"],"difficulty":1},"tags":["javascript","frontend","coding","devtools tech","interview questions","interview preparation","mcq","programming paradigm","tooling","mdn","js paradigm","programming questions","object serialization"],"slug":"what-is-the-process-in-which-an-object-or-data-structure-is-converted-to-series-of-bytes-for-easy-storage-or-network-transfer---qid---tLrb4Y7cnXaPQu3IJy0X","title":"What is the process in which an object or data structure is converted to series of bytes for easy storage or network transfer?","questionId":"tLrb4Y7cnXaPQu3IJy0X"},{"_id":"639da5bd22480f26b3cb006c","content":{"languages":["react"],"difficulty":1},"tags":["","javascript","interview","ui","ux","menu","semantic ui react","semantic ui","css","sass","scss","animations","css framework","machine coding round","react menu","react icons","remix run","simple menu","html css","menu in react"],"slug":"how-to-create-a-vertical-menu-in-react-js-or-beginner-frontend-coding-challenge-or-ui-machine-coding-round-or-javascript---qid---osSDjJQnxRKhlBZvCKNW","title":"How to create a vertical menu in React.js? | Beginner Frontend Coding Challenge | UI Machine Coding Round | JavaScript","questionId":"osSDjJQnxRKhlBZvCKNW"},{"_id":"62b1ca18d3473370ac368c1f","content":{"languages":["react","html"],"difficulty":4},"tags":["javascript","react","frontend coding challenge","ui","js","js fundamentals","codedamn","frontend masters","egghead","react tabs","tabs","pagination","card","card example","frontend interview question"],"slug":"how-to-build-a-ui-card-with-tabs-or-frontend-coding-challenge-or-javascript-interview-question-or-react---qid---7NrTygmpStPLFdWWNcts","title":"How to build a UI Card with Tabs? | Frontend Coding Challenge | JavaScript Interview Question | React","questionId":"7NrTygmpStPLFdWWNcts"}],"resources":[{"_id":"5f202d78cbec5f7ffc0c2fbd","content":{"difficulty":1,"domain":2,"type":2},"tags":["Lazy Loading"," Images"," React"," Intersection Observer"],"slug":"implementation-of-lazy-loading-image-oror-react-oror-intersection-observer---rid---iIx8G2ROXtX6ESYTpJ9a","title":"Implementation of Lazy Loading Image || React || Intersection Observer","resourceId":"iIx8G2ROXtX6ESYTpJ9a"},{"_id":"697cfb276cf04a92bb66eba5","content":{"difficulty":4,"domain":1,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","ui","ux","devtools tech","coding interviews","tutorial","guide","documentation","frontend interviews"],"slug":"guide-to-effective-interview-preparation---rid---6CuY8FFJTPvNHD2SuGLK","title":"Guide to Effective Interview Preparation","resourceId":"6CuY8FFJTPvNHD2SuGLK"},{"_id":"5f1dd731cbec5f7ffc0c2fab","content":{"difficulty":2,"domain":3,"type":1,"isInternal":true},"tags":["node.js","express","rest","api","framework","backend","tools","devtools","framework development","build express"],"slug":"build-your-own-expressjs-or-part-2---rid---negw30VulwpaVLRpxxMl","title":"Build your own expressjs | Part 2","resourceId":"negw30VulwpaVLRpxxMl"},{"_id":"6a12e5684b3e6d922c54a0e9","content":{"difficulty":1,"domain":1,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","ui","ux","devtools tech","tutorials","blogs","react","image optimisation","responsive images","web performance"],"slug":"responsive-images-srcset-sizes-and-picture---rid---YlLGKU8oqpo6ivZBG2mI","title":"Responsive Images: srcset, sizes, and picture","resourceId":"YlLGKU8oqpo6ivZBG2mI"},{"_id":"69a7c86a92f33c7d8aa04cd9","content":{"difficulty":1,"domain":1,"type":2,"isInternal":false,"languages":[]},"tags":["javascript","ui","ux","devtools tech","coding","frontend","interview","growth","promotion"],"slug":"how-i-got-promoted-at-my-job---rid---mqhADdzPtZMdtHG2vbuU","title":"How I got promoted at my job?","resourceId":"mqhADdzPtZMdtHG2vbuU"}]}}