Course content

CSS

Make your pages look good. Learn colors, layout, spacing, and how to design for any screen.

📚 Beginner ⏱ 46 lessons · ~8h

What is CSS?

The Simple Version

CSS stands for Cascading Style Sheets. It is the language we use to make HTML pages look beautiful.

If HTML is the structure of your page (headings, paragraphs, images), then CSS is the style - the colors, fonts, spacing, and layout. Without CSS, every website would look like a plain text document from the 1990s.

Think of it like this: HTML is like the walls and rooms of a house. CSS is the paint, curtains, tiles, and decorations. The house stands without decoration, but CSS makes it a home.

Or think about matatus in Nairobi! A plain white minibus and a fully decorated matatu with graffiti art, LED lights, and custom paint both drive the same route. But one catches your eye from a block away. That decorated matatu? That is what CSS does to your HTML.

What's Really Happening

When a browser loads a web page, it first reads the HTML to understand the structure - what elements exist and how they are organized. Then it reads the CSS to know how to display those elements.

CSS controls virtually every visual aspect of a page:

  • Colors - text color, background color
  • Fonts - font family, size, weight
  • Spacing - padding, margins, gaps
  • Layout - where things appear on the page
  • Animations - transitions, movement, effects
  • Responsiveness - how the page adapts to different screen sizes
Why "Cascading"? The word "cascading" means that styles flow downward. If you set a color on the <body>, all elements inside it inherit that color unless they have their own. Styles also cascade by priority - more specific rules override general ones. We will explore this in detail in later lessons.

CSS was created in 1996 by Håkon Wium Lie while working at CERN. Before CSS, developers had to use HTML attributes like bgcolor and <font> tags to style pages - messy and hard to maintain. CSS separated content (HTML) from presentation (CSS), which was a revolution in web development.

Try It Yourself

Below you can see HTML without any CSS, and then the same HTML with CSS. Click Run to see the result. Try changing the CSS values to see what happens!

HTML/CSS Code
Result

Things to try:

  • Delete everything inside the <style> tags and click Run - see how plain the page looks without CSS!
  • Change background-color: #f0f8ff; to background-color: #ffe6e6;
  • Change color: #1a5276; to color: red;
  • Change font-size: 18px; to font-size: 28px;

Play With Styles

Now try changing colors and fonts on this simple page. Make it your own!

HTML/CSS Code
Result

Things to try:

  • Change the .duka-sign background color to #e74c3c (red) or #3498db (blue)
  • Change the font-family from Georgia, serif to Verdana, sans-serif
  • Add text-decoration: underline; to the h2 rule
  • Change border-radius: 10px; to border-radius: 0px; - notice the sharp corners!

Challenge

Go back to the first editor and try to create your own styled page. Write a short "About Me" page with:

  • A heading with your name in your favorite color
  • A background color that you like
  • A paragraph about yourself with a different font size
  • A highlighted box (like the .highlight div) with a fun fact about you

What You Learned

  • CSS stands for Cascading Style Sheets - it controls how HTML looks
  • HTML provides structure, CSS provides style
  • CSS controls colors, fonts, spacing, layout, and much more
  • "Cascading" means styles flow from general to specific
  • Without CSS, web pages are plain and unstyled - like a matatu without paint!
  • CSS separates content from presentation, making websites easier to maintain
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

How to Add CSS

The Simple Version

There are three ways to add CSS to your HTML page.

  1. Inline CSS - using the style attribute directly on an HTML element
  2. Internal CSS - using a <style> tag inside the <head> section
  3. External CSS - using a separate .css file linked with a <link> tag
Think of it like cooking: Inline CSS is like adding salt directly to your plate of ugali - it only affects that one serving. Internal CSS is like seasoning the whole pot. External CSS is like having a recipe book that all your family follows - every meal is consistent!

What's Really Happening

1. Inline CSS

Inline styles are written directly on an element using the style attribute. They apply only to that one element.

<p style="color: red; font-size: 20px;">This text is red.</p>

When to use: Quick tests, one-off styles, or when overriding other styles. Generally avoided in production code because it mixes content with presentation.

2. Internal CSS

Internal styles are placed inside a <style> tag in the <head> section. They apply to the entire page.

<head>
  <style>
    p { color: blue; }
    h1 { font-size: 32px; }
  </style>
</head>

When to use: Single-page projects, quick prototypes, or when styles are unique to one page.

3. External CSS

External stylesheets are separate .css files linked to your HTML using a <link> tag. This is the recommended approach for real projects.

<head>
  <link rel="stylesheet" href="styles.css">
</head>

When to use: Always, for real websites! It keeps your code organized and lets multiple pages share the same styles.

Best Practice: Professional developers almost always use external CSS. It keeps HTML clean, makes styles reusable across pages, and is easier to maintain. In this course, our editor uses internal CSS (inside <style> tags) for convenience, but in real projects you would use external files.

Try It Yourself

This example shows inline styles. Each element has its own style attribute. Notice how the CSS is mixed right into the HTML.

HTML/CSS Code
Result

Things to try:

  • Change color: darkgreen; to color: navy; in the h1
  • Add font-family: Arial, sans-serif; to the first paragraph's style
  • Change the background color of the special offer box
  • Notice how messy the code looks with all these inline styles - this is why we prefer other methods!

Internal Stylesheet

Now see the same content styled with an internal stylesheet. All the CSS is in one place inside the <style> tag. Much cleaner!

HTML/CSS Code
Result

Things to try:

  • Compare this code to the inline version above - see how much cleaner the HTML is?
  • Add a new paragraph in the body and give it the class description - it automatically gets styled!
  • Change all the colors in the <style> block - one place controls everything
  • Try adding text-transform: uppercase; to the h1 rule

Challenge

Create a small "Chai Shop" page using an internal stylesheet. Your page should have:

  • A styled heading that says "Duka la Chai" with a warm color
  • A paragraph describing your chai shop (use a class for styling)
  • A menu section with at least 3 items, each styled with a background color
  • Use at least 5 different CSS properties

What You Learned

  • There are 3 ways to add CSS: inline, internal, and external
  • Inline CSS uses the style attribute on individual elements
  • Internal CSS uses a <style> tag in the <head>
  • External CSS uses a separate .css file with a <link> tag
  • External CSS is the best practice for real projects
  • Internal CSS keeps styles organized in one place per page
  • Inline CSS should be used sparingly - it makes code messy
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

CSS Syntax

The Simple Version

Every CSS rule follows the same simple pattern: you pick what to style (the selector), then you say how to style it (the declarations).

selector {
  property: value;
  property: value;
}

That is it! A selector, curly braces { }, and inside them one or more property: value pairs, each ending with a semicolon.

Think of it like giving directions in a market: "The fish seller should put the fish on ice and cover it with a net." The fish seller is the selector (who are we talking to?). "Put on ice" and "cover with net" are the declarations (what should they do?). Each instruction is a separate property-value pair.

What's Really Happening

Let us break down each part of a CSS rule:

The Selector

The selector tells the browser which HTML elements to apply the styles to. It comes before the curly braces.

h1 {  /* h1 is the selector - targets all h1 elements */
  color: blue;
}

The Declaration Block

Everything inside the curly braces { } is called the declaration block. It contains one or more declarations.

Declarations (Property: Value)

Each declaration has two parts separated by a colon:

  • Property - the aspect you want to change (like color, font-size, background-color)
  • Value - what you want to set it to (like red, 20px, #f0f0f0)

The Semicolon

Each declaration must end with a semicolon ;. Forgetting a semicolon is one of the most common CSS mistakes!

Common Mistake: If you forget a semicolon, the browser will try to read the next property as part of the current value. This can cause styles to break in unexpected ways. Always double-check your semicolons!

Tip: You can put multiple declarations on one line, but it is much easier to read when each declaration is on its own line. Good formatting makes debugging easier.

Multiple Rules

You can write as many CSS rules as you need. Each one targets a different selector:

h1 {
  color: navy;
  font-size: 32px;
}

p {
  color: #333;
  line-height: 1.6;
}

body {
  background-color: #fafafa;
  font-family: Arial, sans-serif;
}

Try It Yourself

Practice writing CSS rules with the correct syntax. Try adding more properties to each rule.

HTML/CSS Code
Result

Things to try:

  • Add text-decoration: underline; to the h1 rule
  • Add background-color: #ffffcc; to the p rule
  • Remove a semicolon and click Run - see what breaks!
  • Add a new rule for footer with font-style: italic;

Multiple Selectors Practice

Style different HTML elements using separate CSS rules. Each rule targets a specific element.

HTML/CSS Code
Result

Things to try:

  • Add a rule for h2 that includes text-transform: uppercase;
  • Change ul background to #fdebd0 for a warm Safari feel
  • Add font-weight: bold; to the li rule
  • Create a new <h3> element in the HTML and write a CSS rule for it

Challenge

Write a CSS rule for every HTML element on this list. Each rule must have at least 3 declarations (property-value pairs):

  • body - set font family, background color, and padding
  • h1 - set color, size, and alignment
  • p - set color, line height, and font size
  • ul or ol - set background, padding, and border

What You Learned

  • CSS rules follow the pattern: selector { property: value; }
  • The selector picks which elements to style
  • The declaration block is everything inside { }
  • Each declaration has a property and a value separated by a colon
  • Every declaration must end with a semicolon
  • You can have multiple declarations in one rule
  • You can have multiple rules in one stylesheet
  • Good formatting (one declaration per line) makes CSS easier to read and debug
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

CSS Selectors

The Simple Version

A CSS selector is how you tell the browser which HTML elements you want to style. There are three main types you need to know first.

  • Element selector - targets all elements of a type: p, h1, div
  • Class selector - targets elements with a specific class: .my-class
  • ID selector - targets one unique element: #my-id
Think of it like calling people at a harambee: An element selector is like saying "all women, please stand" - it targets a whole group. A class selector is like saying "everyone wearing a red kanga, please stand" - it targets a specific group you defined. An ID selector is like calling someone by name: "Mama Wanjiku, please stand" - only one person responds.

What's Really Happening

1. Element Selectors

These target all instances of an HTML element on the page. Just write the element name:

p {
  color: #333;
}
/* Targets ALL <p> elements on the page */

h1 {
  font-size: 32px;
}
/* Targets ALL <h1> elements on the page */

2. Class Selectors

Classes let you create reusable styles. In HTML, you assign a class with class="name". In CSS, you select it with a dot . prefix:

/* HTML: <p class="highlight">Text</p> */

.highlight {
  background-color: yellow;
  padding: 10px;
}
/* Targets any element with class="highlight" */

One element can have multiple classes: class="highlight important". And many elements can share the same class.

3. ID Selectors

IDs are for unique elements - only one element should have a given ID on a page. In CSS, use a hash # prefix:

/* HTML: <div id="main-header">...</div> */

#main-header {
  background-color: navy;
  color: white;
  padding: 20px;
}
/* Targets the ONE element with id="main-header" */

Specificity (Which Style Wins?)

When multiple rules target the same element, CSS uses specificity to decide which wins:

Specificity Ranking (lowest to highest):
  1. Element selectors (p, h1) - lowest specificity
  2. Class selectors (.highlight) - medium specificity
  3. ID selectors (#header) - high specificity
  4. Inline styles (style="...") - highest specificity
If an element has both p { color: blue; } and .special { color: red; }, and the element is <p class="special">, the text will be red because class beats element.

Try It Yourself

See how element selectors and class selectors work. Notice how a class can override an element style.

HTML/CSS Code
Result

Things to try:

  • Add class="featured" to the last paragraph - see how it changes
  • Create a new class .mara-green with color: green; and apply it to a paragraph
  • Add class="safari-card warning" to see two classes on one element
  • Notice the paragraph inside .safari-card inherits styles from both the p rule and the card

ID Selectors and Combining

Now try ID selectors and see how specificity works when different selectors compete.

HTML/CSS Code
Result

Things to try:

  • Notice how #main-title styles the h1 uniquely - no other element can have this ID
  • Compare the .important paragraphs inside and outside .content-box
  • Try adding color: purple; to the p rule - do the .important paragraphs change? (No! Class beats element)
  • Add a new id="special" to any paragraph and create a rule for #special
  • Try the grouped selector: add h1, h2 { text-transform: uppercase; }

Challenge

Build a "Kenyan Food Menu" page using all three types of selectors:

  • Use element selectors to set base styles for body, h1, p, and li
  • Create a class called .vegetarian that gives items a green color and a leaf-like style
  • Create a class called .spicy that gives items a red color
  • Use an ID selector for the page title to make it unique and eye-catching
  • Include at least 5 food items: nyama choma, ugali, sukuma wiki, chapati, samosa

What You Learned

  • Element selectors (p, h1) target all elements of that type
  • Class selectors (.classname) target elements with that class - reusable and flexible
  • ID selectors (#idname) target one unique element per page
  • Specificity determines which style wins: ID > Class > Element
  • You can combine selectors like p.highlight for more precision
  • You can group selectors with commas: h1, h2, h3 { }
  • Descendant selectors like .box p target elements inside a container
  • Classes are the most commonly used selector in professional CSS
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

CSS Comments

The Simple Version

Comments in CSS are notes you write for yourself (and your teammates) that the browser completely ignores. They help you explain what your code does, organize sections, and temporarily disable styles without deleting them.

CSS comments start with /* and end with */. Everything between those markers is invisible to the browser.

/* This is a CSS comment  -  the browser ignores this */
p { color: red; } /* This rule makes paragraphs red */
Think of comments like notes in pencil in the margin of your textbook. They don't affect the content of the book - only you can read them when you open it. In a busy Nairobi office, it's like writing a small note next to a filing cabinet: "these files are for the Mombasa project" - helpful for anyone who opens the drawer later, including future-you!

What's Really Happening

Why Use Comments?

Comments serve several important purposes in real projects:

  1. Organize your stylesheet - divide CSS into labeled sections so you can find things quickly
  2. Explain complex rules - why did you write z-index: 99 or that unusual margin?
  3. Temporarily disable styles - comment out a rule to test how things look without it
  4. Leave reminders - /* TODO: make this responsive */
  5. Help teammates - others reading your code understand your thinking

Multi-line Comments

Comments can span multiple lines - everything between /* and */ is ignored:

/*
  Section: Navigation styles
  Author: Amina Wanjiru
  Updated: 2026
*/
nav {
  background-color: #1a1a2e;
}

Commenting Out Code

One of the most useful tricks: temporarily disable a rule by wrapping it in a comment. Great for debugging!

p {
  color: red;
  /* font-size: 24px; */  /* testing: too big? */
  font-size: 16px;
}
Important: CSS does not support // single-line comments like JavaScript does. You must always use /* */ for CSS comments - no exceptions! Using // in CSS will silently break your styles in some browsers.

Organizing a Stylesheet with Comments

Professional developers use comments to create clear sections in large stylesheets:

/* ==========================================
   GLOBAL STYLES
   ========================================== */
body { font-family: Arial, sans-serif; }

/* ==========================================
   NAVIGATION
   ========================================== */
nav { background-color: #1a1a2e; }

/* ==========================================
   HERO SECTION
   ========================================== */
.hero { padding: 4rem 2rem; }

Try It Yourself

See comments in action. Try commenting out individual rules to see what changes, then uncomment them to restore the styles.

HTML/CSS Code
Result

Things to try:

  • Remove the /* and */ around text-transform: uppercase; and click Run - see h1 change!
  • Comment out the entire .menu-item rule by wrapping it: put /* before and */ after the closing }
  • Add a new comment section header like /* Footer styles */ at the bottom
  • Add the TODO class .sold-out { opacity: 0.4; text-decoration: line-through; } and apply it to a menu item

Organizing with Comments

See how a well-commented stylesheet is much easier to navigate. This is how professional stylesheets look.

HTML/CSS Code
Result

Things to try:

  • Notice how the comment sections (/* --- Header --- */, etc.) make it easy to find specific styles
  • Comment out the entire /* --- Highlight box --- */ section and click Run - the box loses all its styling
  • Add a new section /* --- Images --- */ with a rule for img { max-width: 100%; }
  • Change the /* Kenya green */ comment to say what the color is used for

Challenge

Take the CSS below and add proper comments to organize it. Your comments should:

  • Add a header block comment with a title, your name, and the date
  • Add section comments before each logical group of rules (base, header, content, footer)
  • Add inline comments on at least 3 color values explaining what they represent
  • Comment out one rule temporarily and write a note explaining why
  • Add a /* TODO: */ comment for something you would add later

What You Learned

  • CSS comments use /* */ syntax - everything inside is ignored by the browser
  • Comments can be single-line or span multiple lines
  • CSS does not support // comments - always use /* */
  • Use comments to organize your stylesheet into named sections
  • Use comments to explain why a rule exists, not just what it does
  • Use comments to temporarily disable rules when debugging
  • Use /* TODO: */ comments to mark unfinished work
  • Good commenting habits make you a better team member and future-proof your code
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

CSS Colors

The Simple Version

CSS gives you several ways to write colors: by name, by hex code, by RGB values, or by HSL. They all produce colors - just different ways of describing the same thing.

Think of it like describing a kanga fabric color: You could say "it's red", or "it's #FF0000", or "it's rgb(255,0,0)". Same color, different ways to say it. One color, many ways to describe it - just like you might call the same person "Mama Njeri", "the shopkeeper on Moi Avenue", or "the woman in the blue kanga" depending on context.

What's Really Happening

1. Color Names

CSS has 140+ built-in color names you can use directly:

p { color: red; }
h1 { color: navy; }
div { background-color: lightgreen; }

2. Hex Codes

Hex codes are the most common format in professional CSS. They start with # followed by 6 hex digits (0–9 and a–f) representing red, green, and blue:

/* #RRGGBB */
h1 { color: #1a5276; }   /* dark blue */
p  { color: #c0392b; }   /* deep red */
.box { background-color: #f39c12; } /* orange */

3. RGB

RGB lets you set red, green, blue values from 0 to 255:

p { color: rgb(26, 82, 118); }        /* same as #1a5276 */
.box { background-color: rgb(243, 156, 18); }

4. RGBA (with transparency)

The a in RGBA is alpha - opacity from 0 (invisible) to 1 (fully opaque):

.overlay { background-color: rgba(0, 0, 0, 0.5); } /* 50% transparent black */
.highlight { background-color: rgba(243, 156, 18, 0.3); } /* light orange tint */

5. HSL

HSL stands for Hue (0–360°), Saturation (0–100%), Lightness (0–100%). Great for creating color variations:

.primary { color: hsl(210, 64%, 28%); }
.light   { color: hsl(210, 64%, 60%); } /* same hue, lighter */
.dark    { color: hsl(210, 64%, 15%); } /* same hue, darker */

Try It Yourself

Experiment with different color formats on a Kenyan-themed page.

HTML/CSS Code
Result

Things to try:

  • Change #006600 to hsl(120, 100%, 20%) - same green, different format
  • Add rgba(187, 0, 0, 0.2) as a background color on the card
  • Try color: transparent on an element - it disappears!
  • Change the .white swatch to background-color: #fff (shorthand hex)

Challenge

Build a "Kenyan Sunset" color palette page:

  • Create 5 color swatches showing sunset colors (orange, red, purple, dark blue, gold)
  • Use a different color format for each: name, hex, rgb, rgba, hsl
  • Label each swatch with the color name and code used
  • Use rgba to create a semi-transparent overlay on one element

What You Learned

  • Color names - easy to read, limited selection (red, navy, gold, etc.)
  • Hex codes (#RRGGBB) - most common in professional CSS
  • RGB - rgb(r, g, b) with values 0–255
  • RGBA - adds transparency with a 4th value (0–1)
  • HSL - hsl(hue, saturation%, lightness%) - great for color variations
  • Use color for text, background-color for backgrounds
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Font Family

The Simple Version

Every piece of text on a website uses a font. The font-family property lets you choose which font your text should use. Different fonts give your page a completely different feel - formal, casual, modern, or classic.

There are three main font categories:

  • Serif - fonts with small decorative lines at the ends of letters (like Times New Roman, Georgia). They feel traditional and formal.
  • Sans-serif - fonts without those decorative lines (like Arial, Verdana). They feel clean and modern.
  • Monospace - every letter takes up the same width (like Courier New). Used for code.
Choosing a font is like choosing clothes for an interview - the style sets the mood. A serif font is like wearing a suit (formal), a sans-serif font is like a smart casual outfit (modern and clean), and monospace is like a uniform (consistent and technical).

What's Really Happening

When the browser reads your font-family property, it looks for that font on the user's computer. But not everyone has the same fonts installed! That is why we use font stacks - a list of fonts in order of preference.

Web-safe fonts are fonts that come pre-installed on almost every computer:

  • Arial - the most common sans-serif font
  • Verdana - wide and easy to read on screens
  • Georgia - an elegant serif font designed for screens
  • Times New Roman - the classic serif font (newspapers, documents)
  • Courier New - the standard monospace font

Font stacks work like a fallback system:

font-family: "Segoe UI", Arial, sans-serif;

This tells the browser: "Use Segoe UI if you have it. If not, try Arial. If that is also missing, use any sans-serif font."

Good to know: Font names with spaces (like "Times New Roman") must be wrapped in quotes. The generic family name at the end (serif, sans-serif, monospace) should never have quotes - it is a CSS keyword, not a font name.

Try It Yourself

See how different font families change the look and feel of text. Try changing the font names to see the difference.

HTML/CSS Code
Result

Things to try:

  • Change Georgia to "Times New Roman" and see the difference
  • Change Arial to Verdana - which one feels wider?
  • Try setting everything to monospace - it looks like a typewriter!

Try More

Now let's see font stacks in action. A font stack is your backup plan when a font is not available.

HTML/CSS Code
Result

Challenge

Create a "Karibu Kenya" tourism page with three sections, each using a different font family.

  • A heading in a serif font for a formal, elegant feel
  • Body text in a sans-serif font for easy reading
  • A section showing a Swahili proverb in a different font from the body text
  • Use proper font stacks with at least 2 fallback fonts for each
  • Include at least one font name with spaces (wrapped in quotes)

What You Learned

  • font-family sets the font for text
  • Serif fonts have decorative lines (Georgia, Times New Roman) - feel formal
  • Sans-serif fonts are clean and modern (Arial, Verdana) - feel casual
  • Monospace fonts have equal-width letters (Courier New) - used for code
  • Font stacks provide fallback fonts in case the first choice is not available
  • Font names with spaces need quotes: "Times New Roman"
  • Always end a font stack with a generic family: serif, sans-serif, or monospace
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Font Size & Weight

The Simple Version

Font size controls how big or small your text appears. Font weight controls how thick or thin the letters are (bold, normal, light). Together, they help you create visual hierarchy - showing readers what is most important.

There are three main ways to set font size:

  • px (pixels) - a fixed size that stays the same no matter what. Like measuring in centimeters.
  • em - relative to the parent element's font size. If the parent is 16px, then 2em = 32px.
  • rem - relative to the root (html) element's font size. More predictable than em.
Think of it this way: px is like measuring in centimeters - it is always the same, fixed, absolute. em and rem are like saying "twice as big as the parent" or "half the size of the root."

What's Really Happening

Pixels (px) are the simplest unit. font-size: 16px means the text will be exactly 16 pixels tall. It does not change based on anything else. This is great when you want precise control.

Em (em) is relative to the parent element's font size. This means em values can compound - if a parent is 1.5em and a child inside it is also 1.5em, the child ends up being 1.5 x 1.5 = 2.25 times the root size. This can get confusing!

Rem (rem) stands for "root em." It is always relative to the root <html> element (usually 16px by default). 1.5rem is always 24px (16 x 1.5), no matter how deeply nested the element is. This makes rem more predictable and is the preferred unit for most developers today.

Font weight controls boldness:

  • font-weight: normal (same as 400) - standard thickness
  • font-weight: bold (same as 700) - thick and strong
  • Numbers from 100 to 900 give you fine control: 100 is thinnest, 900 is thickest
  • Common values: 300 (light), 400 (normal), 500 (medium), 600 (semi-bold), 700 (bold)

Good to know: Not all fonts support all weight values. Most web-safe fonts only have normal (400) and bold (700). If you set font-weight: 300 but the font does not have a light version, the browser will use the closest available weight. Google Fonts often provide many weight options - we will learn about those in Lesson 11!

Try It Yourself

Compare px, em, and rem side by side. Change the values and see what happens!

HTML/CSS Code
Result

Things to try:

  • Change the root font-size in html to 20px - watch all rem values get bigger!
  • Change the parent's font-size to 30px - the em child changes too
  • Notice that px values never change, no matter what the parent or root is

Try More

Now let's explore font-weight. See how different weights make text look thicker or thinner.

HTML/CSS Code
Result

Challenge

Create a safari tour brochure page.

  • A main title using rem units and font-weight: 700
  • A subtitle with a lighter weight (300 or 400)
  • Tour descriptions using em units for font size
  • Prices displayed large and bold (use px for the price)
  • Small print / details in a lighter weight and smaller size
  • Use at least two different size units (px, em, or rem)

What You Learned

  • px is a fixed, absolute size - always the same regardless of context
  • em is relative to the parent element's font size - can compound when nested
  • rem is relative to the root element's font size - predictable and preferred
  • font-weight: normal = 400, font-weight: bold = 700
  • Weight values range from 100 (thinnest) to 900 (thickest)
  • Use different sizes and weights to create visual hierarchy - showing readers what to look at first
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Text Styling

The Simple Version

CSS gives you many ways to style text beyond just choosing a font. You can change the color, alignment, decoration (underline, strikethrough), capitalization, and spacing between letters and words.

Here are the key text styling properties:

  • color - changes the text color
  • text-align - aligns text left, center, right, or justify
  • text-decoration - adds underline, overline, line-through, or none
  • text-transform - converts to uppercase, lowercase, or capitalize
  • letter-spacing - space between individual letters
  • word-spacing - space between words
Think of text styling like decorating a sign for your duka (shop). The font is the handwriting style, but text styling is everything else - the color of the paint, whether you underline the name, whether you write in ALL CAPS to grab attention, and how much space you leave between the letters.

What's Really Happening

color sets the text color. You can use color names, hex codes, or rgb values:

color: red;
color: #e74c3c;
color: rgb(231, 76, 60);

text-align controls horizontal alignment within the element:

  • left - default for most languages
  • center - centered
  • right - aligned to the right
  • justify - stretched to fill the full width, like a newspaper column

text-decoration adds or removes visual decorations:

  • underline - line below the text
  • overline - line above the text
  • line-through - line through the middle, like crossing something out
  • none - removes all decoration (commonly used to remove underlines from links)

text-transform changes the capitalization without editing the HTML:

  • uppercase - ALL LETTERS BECOME CAPITALS
  • lowercase - all letters become small
  • capitalize - First Letter Of Each Word Is Capitalized

Good to know: text-decoration: none is one of the most commonly used CSS declarations. By default, links (<a> tags) have an underline. Most websites remove it with text-decoration: none and add their own styling.

Try It Yourself

Play with text color and alignment. Try changing the values to see different effects!

HTML/CSS Code
Result

Things to try:

  • Change the color values to different hex codes or color names
  • Try text-align: center on the justified paragraph
  • Change all paragraphs to the same alignment and see how it feels

Try More

Now let's explore decoration, transform, and spacing properties.

HTML/CSS Code
Result

Challenge

Create a styled duka (shop) sign page with the following.

  • A shop name in uppercase with wide letter-spacing
  • A tagline centered with a different color
  • At least three products with prices - one product should show an old price with line-through and a new price
  • Use text-transform: capitalize on product names
  • Remove the underline from at least one link using text-decoration: none
  • Include Kiswahili text throughout - mix the languages!

What You Learned

  • color changes text color using names, hex, or rgb values
  • text-align controls alignment: left, center, right, or justify
  • text-decoration adds underline, overline, line-through, or removes them with none
  • text-transform converts text to uppercase, lowercase, or capitalize
  • letter-spacing controls space between letters
  • word-spacing controls space between words
  • text-decoration: none is essential for styling links
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Line Height & Spacing

The Simple Version

The space between and around your text makes a huge difference in how easy it is to read. line-height controls the space between lines of text, while letter-spacing, word-spacing, and text-indent fine-tune the spacing within your text.

The key spacing properties:

  • line-height - space between lines of text
  • letter-spacing - space between individual characters
  • word-spacing - space between words
  • text-indent - indentation of the first line in a paragraph
Think of line-height like the lines in a notebook. A notebook with wide lines (wide ruling) is easier to read and write in than one with very narrow lines. More space between lines = easier to read!

What's Really Happening

line-height can be set in several ways:

  • line-height: 1.5 - a unitless number (recommended!). This means 1.5 times the font size. If font is 16px, line height is 24px.
  • line-height: 24px - a fixed pixel value
  • line-height: 150% - percentage of the font size

The recommended approach is to use a unitless number like 1.5 or 1.6. This way, the line height automatically scales if the font size changes. For body text, a line-height between 1.4 and 1.8 is usually comfortable. The default is about 1.2, which is often too tight for reading.

letter-spacing adjusts the space between each character. Positive values spread letters apart, negative values bring them closer. It is commonly used on uppercase headings.

word-spacing does the same but between whole words. The default value is normal (about 0.25em). You rarely need to change this, but it can be useful for specific design effects.

text-indent indents only the first line of a paragraph, like the start of a paragraph in a book or essay.

Good to know: Poor spacing is one of the most common reasons a website feels "off" or hard to read. A simple change from line-height: 1.2 to line-height: 1.6 can transform a page from cramped to open and inviting.

Try It Yourself

See how line-height changes the readability of text. Compare tight, normal, and generous spacing.

HTML/CSS Code
Result

Things to try:

  • Change the tight line-height to 1.6 and see how much better it reads
  • Try line-height: 3.0 - at some point, too much space is also bad!
  • Notice which line-height feels most natural and comfortable to read

Try More

Combine all the spacing properties to create beautifully readable text.

HTML/CSS Code
Result

Challenge

Create a Swahili proverb display page:

  • A title with uppercase text and wide letter-spacing
  • At least three Swahili proverbs with their English translations
  • Use line-height: 1.6 or higher for comfortable reading
  • Use text-indent on explanation paragraphs below each proverb
  • Style the proverbs differently from the explanations (different font, size, or color)
  • Use word-spacing on at least one element for a design effect

What You Learned

  • line-height controls space between lines - use 1.4 to 1.8 for readable body text
  • Use a unitless number for line-height (like 1.6) so it scales with font size
  • letter-spacing adjusts space between characters - great for uppercase headings
  • word-spacing adjusts space between words
  • text-indent indents the first line of a paragraph
  • Good spacing is the difference between amateur and professional-looking text
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Google Fonts

The Simple Version

In Lesson 7, you learned about web-safe fonts - the fonts that come pre-installed on computers. But what if you want a more unique, beautiful font? That is where Google Fonts comes in.

Google Fonts is a free library of over 1,500 fonts that you can use on any website. Instead of relying only on fonts installed on the user's computer, Google Fonts loads the font from the internet. This means everyone sees the same beautiful font, no matter what computer or phone they are using.

There are two ways to add Google Fonts to your project:

  • The <link> method - add a link tag in your HTML <head>
  • The @import method - add an import rule at the top of your CSS
Think of Google Fonts like a clothing rental service. Instead of only wearing clothes you own (web-safe fonts), you can borrow beautiful outfits from a huge collection (Google Fonts) and wear them for free. Everyone who visits your website will see the outfit you chose!

What's Really Happening

Method 1: The <link> tag (recommended for most projects)

You add this in your HTML <head> section, before your own stylesheet:

<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">

Then in your CSS:

body {
    font-family: 'Roboto', sans-serif;
}

Method 2: The @import rule (add at the very top of your CSS file)

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');

Popular Google Fonts:

  • Roboto - clean, modern, used by Android and many Google products
  • Open Sans - friendly and highly readable, great for body text
  • Poppins - geometric and modern, popular for headings
  • Lato - warm and stable, works well for both headings and body
  • Montserrat - urban and bold, excellent for headings
  • Playfair Display - elegant serif, perfect for titles

Good to know: The code editor below uses iframes, which cannot load external Google Fonts. So we will show you the correct syntax and use web-safe fonts as a visual demonstration. When you build real projects in your own code editor, the Google Fonts will work perfectly!

Try It Yourself

This example shows the @import syntax for Google Fonts. The actual fonts will not load in this editor, but you can see the correct code pattern. The web-safe fallback fonts will display instead.

HTML/CSS Code
Result

Things to try:

  • Change the fallback fonts to see how different web-safe fonts look
  • Try Georgia for the body text instead of the sans-serif
  • Add more font weight variations (300, 400, 600, 700)

Try More

Here is a typography showcase showing how you would combine different fonts for headings, body text, and accents.

HTML/CSS Code
Result

Challenge

Create a styled landing page for a fictional Kenyan business:

  • Write the correct @import syntax in a CSS comment (showing you know how to do it)
  • Use a serif font for headings and a sans-serif font for body text (web-safe fonts as demonstration)
  • Include a business name, tagline, description, and a price section
  • Apply everything you have learned: font-family, font-size (using rem), font-weight, line-height, letter-spacing, text-align, and text-transform
  • Make it bilingual - English and Kiswahili!
  • Show at least three different font weights

What You Learned

  • Google Fonts is a free library of 1,500+ fonts you can use on any website
  • Add fonts with <link> in HTML or @import in CSS
  • Popular fonts: Roboto, Open Sans, Poppins, Lato, Montserrat, Playfair Display
  • Always include a web-safe fallback font in your font stack
  • Pair a heading font with a body font for professional typography
  • Only load the font weights you need to keep your website fast
  • Visit fonts.google.com to browse and get the code
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

The Box Model

The Simple Version

In CSS, every single element is a box. Whether it is a heading, a paragraph, an image, or a link - the browser treats it as a rectangular box. The CSS Box Model describes the four layers that make up every box: content, padding, border, and margin.

Think of it like this: Imagine a picture frame hanging on a wall. The picture itself is the content. The mat (the space between the picture and the frame) is the padding. The frame itself is the border. And the space between frames on the wall is the margin.

What's Really Happening

When the browser renders an element, it builds the box from the inside out:

  • Content - The actual text, image, or other content inside the element. Its size is controlled by width and height.
  • Padding - Transparent space between the content and the border. It pushes the content inward, away from the edges.
  • Border - A visible (or invisible) line that wraps around the padding. It has width, style, and color.
  • Margin - Transparent space outside the border. It pushes other elements away.
Total width calculation: By default (using content-box), the total width of an element is: width + padding-left + padding-right + border-left + border-right + margin-left + margin-right. This is why elements sometimes end up larger than you expect! We will learn how to fix this with box-sizing: border-box in Lesson 16.

You can visualize the box model in any browser by right-clicking an element, selecting "Inspect", and looking at the box model diagram in the developer tools. It shows each layer with its exact pixel values.

Try It Yourself

See the box model layers visualized with colored backgrounds. Each color represents a different layer of the box.

HTML/CSS Code
Result

Things to try:

  • Change the padding in .margin-layer from 30px to 10px - watch the margin area shrink
  • Change the border width from 8px to 20px - see the border get thicker
  • Change the padding in .padding-layer from 30px to 5px - the padding shrinks

Try More

Now let's inspect the box model on real elements. Each box below has different padding, border, and margin values.

HTML/CSS Code
Result

Things to try:

  • Set all three boxes to padding: 20px; border: 3px solid black; margin: 15px; - now they are equal
  • Add width: 200px; to .box - notice the boxes are the same content width but different total widths
  • Try setting margin: 0; on all boxes - they stack right against each other

Challenge

Create a "product card" that clearly demonstrates the box model. Your card should have:

  • A width of 250px
  • padding of 20px so the text does not touch the edges
  • A border of 3px solid in a color of your choice
  • A margin of 30px auto to center it on the page
  • Calculate the total width of the card (content + padding + border)

What You Learned

  • Every HTML element is a rectangular box in CSS
  • The box model has four layers: content, padding, border, and margin
  • Content is where text and images live
  • Padding is the space between content and border
  • Border is the visible edge around the element
  • Margin is the space outside the border that separates elements
  • By default, total width = content width + padding + border + margin
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Padding

The Simple Version

Padding is the space between the content of an element and its border. It creates breathing room inside the box, so your text and images do not press against the edges.

You can set padding on all four sides at once, or control each side individually. The padding shorthand lets you write it in one line.

Think of it like this: Padding is like the cushion inside a sofa. The frame of the sofa is the border, and the cushion (padding) keeps you comfortable and away from the hard edges. Without cushion, you would sit right on the wooden frame! Similarly, without padding, text presses right against the border.

What's Really Happening

CSS gives you several ways to set padding:

  • padding: 10px; - All four sides get 10px
  • padding: 10px 20px; - Top/bottom get 10px, left/right get 20px
  • padding: 10px 20px 30px; - Top 10px, left/right 20px, bottom 30px
  • padding: 10px 20px 30px 40px; - Clockwise from top: top 10px, right 20px, bottom 30px, left 40px

You can also set each side individually:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left
Clockwise trick: Remember the order for 4-value shorthand by thinking of a clock: Top, Right, Bottom, Left - it goes clockwise starting from 12 o'clock. Or just remember the word TRouBLe (T-R-B-L).

Padding is always transparent - it takes the background color of the element. Unlike margin, padding cannot have negative values.

Try It Yourself

See how different padding shorthand values affect the spacing inside boxes.

HTML/CSS Code
Result

Things to try:

  • Change padding: 10px; to padding: 50px; - the box grows much larger
  • Change padding: 10px 40px; to padding: 40px 10px; - more space on top/bottom instead of sides
  • Try padding: 0; on any box - the text presses right against the border

Try More

Now let's use individual padding properties to see exactly which side gets affected.

HTML/CSS Code
Result

Things to try:

  • Add padding-bottom: 60px; to the .top-only box - now it has space on top and bottom
  • Change .mixed to use the shorthand: padding: 10px 50px 30px 70px; - same result, one line!
  • Set all boxes to padding: 20px; and see how uniform they become

Challenge

Create a notification banner (like you see on websites) that has:

  • Different padding on each side - more on left (to leave room for an icon) and less on top/bottom
  • A background color and a left border (hint: border-left: 4px solid color;)
  • Try writing it first with individual properties (padding-top, etc.) and then rewrite it using the 4-value shorthand

What You Learned

  • Padding is the space between content and border - inside the box
  • padding: 10px; sets all four sides equally
  • padding: 10px 20px; sets top/bottom and left/right
  • padding: 10px 20px 30px 40px; goes clockwise (TRouBLe: Top, Right, Bottom, Left)
  • Individual properties: padding-top, padding-right, padding-bottom, padding-left
  • Padding is always transparent and takes the element's background color
  • Padding cannot be negative
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Borders

The Simple Version

Borders are the visible lines that wrap around elements, sitting between the padding and the margin. You can control a border's width, style, and color - and even round the corners with border-radius.

The shorthand border: 2px solid black; sets width, style, and color all at once. You can also style each side of the border independently.

Think of it like this: Borders are like the fence around a shamba (farm). They define where your property starts and ends. Some fences are tall and thick (wide borders), some are made of wire (dashed), some are wooden posts with gaps (dotted), and some are decorative stone walls (double, groove, ridge). You choose the fence style that fits your shamba!

What's Really Happening

The border shorthand combines three properties:

  • border-width - How thick the border is (e.g., 1px, 3px, medium)
  • border-style - The pattern of the line: solid, dashed, dotted, double, groove, ridge, inset, outset, or none
  • border-color - The color of the border
Important: The border-style property is required for a border to appear. Even if you set a width and color, without a style the border remains invisible. The most common style is solid.

You can target individual sides with border-top, border-right, border-bottom, and border-left. Each of these also accepts the shorthand format, like border-bottom: 3px dashed red;.

border-radius rounds the corners of the border. A value of 50% on a square element creates a circle. You can set different radii for each corner.

Try It Yourself

Explore all the different border styles CSS offers. Each box below uses a different border-style.

HTML/CSS Code
Result

Things to try:

  • Change the border width from 3px to 10px on any box - see how thick it gets
  • Change .solid to border: 3px solid red;
  • Try adding border-style: dashed solid; - top/bottom are dashed, left/right are solid

Try More

Now let's explore border-radius to make rounded corners, circles, and creative shapes.

HTML/CSS Code
Result

Things to try:

  • Change .circle to border-radius: 30%; - it becomes a rounded square instead of a circle
  • Try border-radius: 50px 0; on .fancy - a leaf-like shape appears
  • Change the .card left border color to #27ae60 for a success card, or #f39c12 for a warning card

Challenge

Create a set of three status badges using creative borders:

  • A "Success" badge with a green border and rounded corners
  • A "Warning" badge with an orange dashed border
  • A "Error" badge with a red double border and a circle shape
  • Each badge should have appropriate padding and text centered inside

What You Learned

  • The border shorthand sets width, style, and color in one line
  • Border styles include: solid, dashed, dotted, double, groove, ridge, inset, outset, and none
  • You must set a border-style for the border to appear
  • Target individual sides with border-top, border-right, border-bottom, border-left
  • border-radius rounds corners - use 50% for a perfect circle
  • You can set different radii for each corner
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Margin

The Simple Version

Margin is the space outside the border of an element. It pushes other elements away, creating distance between boxes. The shorthand works exactly like padding (clockwise: top, right, bottom, left).

A special trick: margin: auto can center a block element horizontally on the page. This is one of the most commonly used CSS techniques.

Think of it like this: Imagine a row of market stalls at a soko (market). Each stall needs space around it so customers can walk between them. That space between stalls is the margin. If one stall has a big margin, there is a wide pathway around it. If the margin is zero, the stalls are pressed together - no room to walk!

What's Really Happening

Margin uses the same shorthand as padding:

  • margin: 10px; - All four sides
  • margin: 10px 20px; - Top/bottom, left/right
  • margin: 10px 20px 30px 40px; - Clockwise: top, right, bottom, left
  • margin: 20px auto; - 20px top/bottom, auto-center left/right
Margin collapse: When two vertical margins touch (the bottom margin of one element meets the top margin of the next), they collapse into a single margin. The larger one wins. For example, if one element has margin-bottom: 30px and the next has margin-top: 20px, the space between them is 30px, not 50px. This only happens with vertical (top/bottom) margins, never horizontal (left/right).

Unlike padding, margin can be negative. A negative margin pulls the element in that direction, overlapping with other elements. This is a powerful technique but should be used carefully.

margin: auto works for horizontal centering only when the element has a defined width and is a block-level element. The browser divides the remaining space equally between left and right margins.

Try It Yourself

See how margins create space between elements and how margin: auto centers a box.

HTML/CSS Code
Result

Things to try:

  • Change .centered width to 400px - it stays centered but gets wider
  • Remove width: 250px from .centered - margin: auto no longer centers it
  • Change the negative margin from -15px to -30px - even more overlap
  • Try margin: 0; on all boxes - they stack with no space between them

Try More

Watch margin collapse in action. When vertical margins meet, they do not add up - the larger one wins.

HTML/CSS Code
Result

Things to try:

  • Change Box A's margin-bottom to 25px (same as Box B's top) - the gap is still 25px, not 50px
  • Change Box B's margin-top to 60px - now Box B's margin wins and the gap is 60px
  • Remove the border and padding from .parent in the second example - margins collapse again

Challenge

Build a simple page layout with three content cards:

  • Each card should be 300px wide and centered with margin: auto
  • Cards should have 30px of vertical margin between them
  • The first card should have margin-top: 0 and the last card should have margin-bottom: 0
  • Can you predict if margin collapse will affect the spacing between your cards?

What You Learned

  • Margin is the space outside the border - it pushes other elements away
  • Margin shorthand works the same as padding (clockwise: top, right, bottom, left)
  • margin: auto horizontally centers a block element with a set width
  • Margin collapse: when vertical margins meet, the larger one wins (they do not add up)
  • Margins can be negative, pulling elements closer or overlapping them
  • Margin collapse can be prevented with borders, padding, or other techniques
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Box Sizing

The Simple Version

The box-sizing property controls how the total size of an element is calculated. By default, CSS uses content-box, where width only applies to the content - padding and border are added on top. This makes elements bigger than you expect!

With border-box, the width includes content, padding, and border. If you set width: 300px, the element is exactly 300px wide - no surprises. This is why almost every modern website uses border-box.

Think of it like this: Imagine you are building a house and you have a plot that is exactly 10 meters wide. With content-box, you measure 10 meters for the rooms inside, then add walls on top - your house ends up wider than the plot! With border-box, you measure 10 meters for the total, including the walls - everything fits perfectly.

What's Really Happening

There are two values for box-sizing:

  • content-box (default) - width and height apply to the content only. Total size = content + padding + border.
  • border-box - width and height include content + padding + border. The browser shrinks the content area to make everything fit within the specified width.
The universal fix: Almost every modern CSS file starts with this reset:

*, *::before, *::after { box-sizing: border-box; }

This applies border-box to every element on the page. It makes layouts much more predictable because width: 50% always means exactly 50% - regardless of padding or borders.

Note that margin is never included in either box model. Margin is always extra space outside the element.

The difference becomes especially important when building layouts with percentage widths. Two width: 50% elements should sit side by side - but with content-box, adding any padding or border pushes them past 100% and they wrap to a new line!

Try It Yourself

See the difference between content-box and border-box side by side. Both boxes have width: 300px, but their total sizes are different.

HTML/CSS Code
Result

Things to try:

  • Increase padding to 40px - the content-box grows even wider, while border-box stays at 300px
  • Increase border to 20px - content-box overflows while border-box stays put
  • Change .content-box-demo to box-sizing: border-box - now both boxes are the same size

Try More

See how border-box makes building card layouts much easier. Without it, equal-width cards break.

HTML/CSS Code
Result

Things to try:

  • Remove the universal *, *::before, *::after { box-sizing: border-box; } reset - the top cards will break too
  • Add box-sizing: border-box; to .broken-card - the red cards fix themselves
  • Try increasing the padding to 40px on both card types - border-box still works, content-box gets worse

Challenge

Build a two-column layout using the border-box reset:

  • Start with the universal reset: *, *::before, *::after { box-sizing: border-box; }
  • Create a sidebar that is 30% wide and a main content area that is 70% wide
  • Add 20px of padding and a 2px border to both sections
  • Verify they sit side by side without overflowing (hint: use display: flex on the parent)
  • Now try removing the border-box reset - watch the layout break!

What You Learned

  • content-box (default): width = content only - padding and border are added on top
  • border-box: width = content + padding + border - total size is exactly what you set
  • Margin is never included in either box model
  • The universal reset *, *::before, *::after { box-sizing: border-box; } is used on nearly every modern website
  • border-box makes percentage-based layouts predictable and reliable
  • Without border-box, adding padding or border to elements with percentage widths causes overflow
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Background Color

The Simple Version

The background-color property sets the background color of any HTML element. You can use named colors like red, hex codes like #ff0000, or RGB values like rgb(255, 0, 0).

Every element on your page can have its own background color - the body, divs, paragraphs, headings, spans, and more. If you do not set a background color, it defaults to transparent, so you see whatever is behind it.

Think of it like this: Setting a background color is like painting the walls of a room. Each room (element) in your house (web page) can have its own wall color. The living room can be blue, the bedroom green, and the kitchen yellow.

What's Really Happening

CSS gives you several ways to specify a background color:

  • Named colors: background-color: red; - there are 147 named colors in CSS
  • Hex codes: background-color: #e74c3c; - six-digit hexadecimal (or three-digit shorthand like #f00)
  • RGB: background-color: rgb(231, 76, 60); - red, green, blue values from 0 to 255
  • HSL: background-color: hsl(6, 78%, 57%); - hue (0–360), saturation, lightness
  • RGBA: background-color: rgba(231, 76, 60, 0.5); - like RGB but with alpha (transparency) from 0 to 1
  • HSLA: background-color: hsla(6, 78%, 57%, 0.5); - like HSL with alpha
Transparency matters! Using rgba() or hsla() lets you make a background semi-transparent. The fourth value (alpha) controls how see-through it is: 1 is fully opaque, 0 is fully invisible, and 0.5 is half-transparent. This is useful for overlays, glass effects, and layered designs.

The background-color fills the entire content area plus padding of an element (up to the border). If you have set box-sizing: border-box;, it still only fills inside the border. The margin area is always transparent.

Try It Yourself

Each element below has a different background color using different color formats. Try changing the values!

HTML/CSS Code
Result

Things to try:

  • Change tomato to other named colors like coral, steelblue, or gold
  • Change the hex color #2ecc71 to #9b59b6 (purple)
  • Change the body background from #f5f5f5 to #1a1a2e (dark) - notice how different it feels!

Try More

Now let's explore transparent backgrounds with rgba(). The boxes below are layered on top of a colored background - watch how the alpha value changes the effect.

HTML/CSS Code
Result

Things to try:

  • Change the .scene background to #3498db or #2ecc71 - notice how the transparent boxes adapt!
  • Change rgba(0, 0, 0, 0.5) to rgba(255, 255, 255, 0.5) for a white glass effect
  • Try rgba(255, 0, 0, 0.3) for a red tint overlay

Challenge

Create a simple page that looks like a set of paint swatches from a hardware store. Build at least 5 colored boxes, each using a different color format:

  • One with a named color
  • One with a hex code
  • One with rgb()
  • One with hsl()
  • One with rgba() showing transparency over a colored background

What You Learned

  • background-color sets the background color of any element
  • You can use named colors, hex codes, rgb(), and hsl() to specify colors
  • rgba() and hsla() add an alpha channel for transparency
  • Alpha values range from 0 (invisible) to 1 (fully opaque)
  • Background color fills the content and padding area, but not the margin
  • If no background-color is set, the default is transparent
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Background Images

The Simple Version

The background-image property lets you place an image behind the content of any element. You use background-image: url('path/to/image.jpg'); to set it.

But placing the image is just the start. You also need to control how big it appears (background-size), whether it repeats (background-repeat), and where it sits (background-position). These properties work together to give you full control.

Think of it like this: Imagine you are putting up wallpaper in a room. You choose the pattern (background-image), decide if it should cover the whole wall or just a section (background-size), whether the pattern repeats or appears once (background-repeat), and where it starts on the wall (background-position).

What's Really Happening

Here are the key background image properties:

  • background-image: url('image.jpg') - sets the image (can also use gradients or SVG data URIs)
  • background-size:
    • cover - scales to fill the entire element (may crop edges)
    • contain - scales to fit entirely inside the element (may leave gaps)
    • 200px 100px - specific width and height
    • 50% - relative to the element size
  • background-repeat:
    • repeat - tiles in both directions (default)
    • no-repeat - shows image once
    • repeat-x - tiles horizontally only
    • repeat-y - tiles vertically only
  • background-position: center, top left, 50% 50%, 20px 10px
The background shorthand: You can combine all background properties in one line: background: url('img.jpg') no-repeat center/cover;. The order is: color, image, repeat, position/size. The shorthand is convenient but can be harder to read, so many developers prefer writing each property separately for clarity.

You can also layer multiple backgrounds by separating them with commas. The first background listed appears on top. This is powerful for combining patterns, overlays, and images.

Try It Yourself

Since we are working inside an iframe, we will use inline SVG data URIs as background images. These work just like real image files! Try changing the background-size and background-repeat values.

HTML/CSS Code
Result

Things to try:

  • Change background-repeat: repeat; to no-repeat on the stars box
  • Change background-size: 150px 150px; to cover on the diamond box
  • Change repeat-x to repeat-y on the dots box
  • Change background-position: center; to top left or bottom right

Try More

Now let's try multiple backgrounds and the background shorthand. You can stack several background images on one element!

HTML/CSS Code
Result

Things to try:

  • Change background-size: cover; to contain on the scene box - notice the difference!
  • Remove one of the background layers from the multi-bg element
  • Change the gradient direction from 135deg to to right or to bottom

Challenge

Create a "business card" style element with:

  • A subtle pattern background using an SVG data URI (dots, lines, or your own design)
  • Use background-size to control the pattern scale
  • Use background-repeat to tile it
  • Add text on top with your name and a title
  • Try layering a second background (hint: use multiple backgrounds with a comma)

What You Learned

  • background-image: url() sets a background image on any element
  • background-size controls image scaling - cover fills, contain fits
  • background-repeat controls tiling - repeat, no-repeat, repeat-x, repeat-y
  • background-position controls where the image sits - center, top left, etc.
  • The background shorthand combines all properties in one line
  • You can layer multiple backgrounds with commas - first listed appears on top
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Gradients

The Simple Version

A gradient is a smooth transition between two or more colors. Instead of a flat background color, you get a beautiful color blend. CSS gives you two main types: linear gradients (colors flow in a straight line) and radial gradients (colors flow outward from a center point).

Gradients are set with background-image (or the background shorthand), not background-color, because CSS treats gradients as images.

Think of it like this: Picture a Nairobi sunset - the sky does not jump from blue to orange to red. The colors blend smoothly into each other. That is exactly what a CSS gradient does. A linear gradient is like the horizon line blending colors left to right. A radial gradient is like the sun itself, with colors radiating outward from the center.

What's Really Happening

Linear gradients flow in a direction you choose:

  • linear-gradient(to right, red, blue) - left to right
  • linear-gradient(to bottom, red, blue) - top to bottom (default)
  • linear-gradient(to bottom right, red, blue) - diagonal
  • linear-gradient(45deg, red, blue) - at a specific angle
  • linear-gradient(to right, red, yellow, green) - multiple color stops

Radial gradients radiate from a center point:

  • radial-gradient(circle, red, blue) - circular shape
  • radial-gradient(ellipse, red, blue) - elliptical (default)
  • radial-gradient(circle at top left, red, blue) - from a specific position
Color stops with percentages: You can control exactly where each color starts and stops. For example, linear-gradient(to right, red 0%, red 33%, white 33%, white 66%, green 66%, green 100%) creates hard stripes with no blending - perfect for creating flag patterns! Without percentages, colors are evenly distributed.

Gradients can be used anywhere you would use background-image. You can even layer multiple gradients on the same element, just like with background images.

Try It Yourself

Explore different linear gradient directions, angles, and color combinations. Try the Kenyan flag!

HTML/CSS Code
Result

Things to try:

  • Change to bottom to to right or to top left
  • Change 45deg to 90deg, 180deg, or 270deg
  • Add more colors to any gradient - just separate them with commas
  • Change the sunset colors to create a sunrise (lighter colors on top)

Try More

Now let's explore radial gradients and creative pattern effects!

HTML/CSS Code
Result

Things to try:

  • Change circle to ellipse (or vice versa) on the radial gradients
  • Move the sun position: change 80% 80% to 50% 50% or 20% 30%
  • Change the repeating stripe width from 10px to 5px or 30px
  • Change the polka dot color from #e74c3c to your favorite color

Challenge

Create a page with three creative gradient designs:

  • A Kenyan flag using linear-gradient with hard color stops (black, red, green, white stripes)
  • A sunset scene using a radial gradient for the sun layered over a linear gradient sky
  • A repeating pattern of your choice - stripes, dots, or something creative

What You Learned

  • linear-gradient() creates color blends in a straight line - top to bottom, left to right, or at any angle
  • radial-gradient() creates color blends radiating from a center point
  • You control direction with keywords (to right) or angles (45deg)
  • Color stops with percentages give you precise control over where colors start and end
  • Hard color stops (same percentage for end and start) create stripes instead of blends
  • repeating-linear-gradient() creates repeating stripe patterns
  • Gradients can be layered with multiple backgrounds for creative effects
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Shadows

The Simple Version

CSS shadows add depth to your designs by creating the illusion that elements are floating above the page. There are two types: box-shadow (shadow around an element's box) and text-shadow (shadow behind text).

Both types use the same basic idea: you specify how far the shadow moves horizontally and vertically, how blurry it is, and what color it should be.

Think of it like this: Shadows make flat things look 3D - like how the afternoon sun in Nairobi casts shadows that make buildings look solid and real. A card without a shadow looks painted onto the page. A card with a shadow looks like you could pick it up.

What's Really Happening

box-shadow takes these values in order:

  • offset-x: horizontal distance (positive = right, negative = left)
  • offset-y: vertical distance (positive = down, negative = up)
  • blur-radius: how blurry the shadow is (0 = sharp, higher = softer)
  • spread-radius: how much the shadow grows or shrinks (optional)
  • color: the shadow color (usually with transparency via rgba())

Example: box-shadow: 5px 10px 20px 0px rgba(0, 0, 0, 0.3);

text-shadow is similar but simpler (no spread value):

text-shadow: offset-x offset-y blur-radius color;

Multiple shadows: You can add multiple shadows to one element by separating them with commas: box-shadow: 0 2px 5px rgba(0,0,0,0.2), 0 10px 30px rgba(0,0,0,0.1);. This creates layered depth that looks more natural. The inset keyword makes the shadow appear inside the element: box-shadow: inset 0 2px 5px rgba(0,0,0,0.3);.

Try It Yourself

Explore different box-shadow values on card elements. Change the numbers and see what happens!

HTML/CSS Code
Result

Things to try:

  • Change the blur from 8px to 0px on the subtle shadow - notice the sharp edge!
  • Change the colored shadow to match a red card: rgba(231, 76, 60, 0.4)
  • Add inset before any box-shadow values to flip it inside
  • Change the offset-x from 0 to 10px to shift the shadow to the right

Try More

Now let's explore text-shadow and some creative shadow effects!

HTML/CSS Code
Result

Things to try:

  • Change the glow color from blue to green: use rgba(46, 204, 113, ...)
  • Change the embossed text-shadow to -1px -1px 0px rgba(0,0,0,0.3) for an engraved look
  • Make the Safari card shadow bigger or smaller by changing the blur and spread values

Challenge

Build a set of three "safari destination" cards, each with:

  • A gradient background (from the previous lesson!)
  • A box-shadow that makes the card look like it is floating
  • A heading with text-shadow for readability
  • One card should use an inset shadow for a different feel
  • Bonus: try a colored shadow that matches each card's gradient

What You Learned

  • box-shadow adds shadows around elements: offset-x offset-y blur spread color
  • text-shadow adds shadows behind text: offset-x offset-y blur color
  • Use rgba() for shadow colors to control transparency
  • Multiple shadows separated by commas create layered, realistic depth
  • The inset keyword makes box-shadow appear inside the element
  • Colored shadows that match the element create a modern glowing effect
  • Shadows are essential for making flat designs feel three-dimensional
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Opacity & Visibility

The Simple Version

CSS gives you three different ways to hide or partially hide elements: opacity, visibility, and display: none. They all make things disappear, but each works differently.

Understanding the difference between these three is essential for building interactive, polished web designs.

Think of it like this: Imagine a matatu (minibus) with passengers:

opacity: 0 is like tinted glass - the passenger is still there, still takes up a seat, you just cannot see them through the dark window.

visibility: hidden is like an invisible person sitting in the matatu - you cannot see them, but the seat is still occupied. Nobody else can sit there.

display: none is like removing the seat entirely. The passenger is gone, the seat is gone, and other passengers slide over to fill the space.

What's Really Happening

Here is how the three approaches compare:

  • opacity: 0 to 1 - controls transparency of the entire element and all its children.
    • opacity: 1 = fully visible (default)
    • opacity: 0.5 = 50% transparent
    • opacity: 0 = fully invisible but still takes up space and is clickable
  • visibility: visible | hidden - toggles visibility on or off.
    • Element is invisible but still takes up space in the layout
    • Not clickable when hidden
    • Children can override with visibility: visible
  • display: none - completely removes the element from the layout.
    • Element is invisible and takes up no space at all
    • Other elements collapse into its former space
    • Cannot be animated with CSS transitions
Key difference for animations: opacity can be smoothly animated with CSS transitions (great for fade effects!). visibility can be toggled with a transition delay. But display: none cannot be animated at all - it is an instant on/off switch. This is why opacity is the preferred choice for fade-in and fade-out effects.

An important detail about opacity: it affects the entire element and all its children. If you only want a transparent background, use rgba() or hsla() on background-color instead.

Try It Yourself

See how different opacity values affect elements, and how opacity differs from using rgba() on the background.

HTML/CSS Code
Result

Things to try:

  • Change the opacity: 0 box to 0.05 - can you barely see it?
  • Change the .opacity-card opacity from 0.4 to 0.8 - the text becomes more readable
  • Change the .rgba-card alpha value from 0.4 to 0.1 - background nearly disappears but text stays crisp

Try More

Compare all three hiding methods side by side: opacity: 0, visibility: hidden, and display: none.

HTML/CSS Code
Result

Things to try:

  • Change .hidden-opacity from opacity: 0 to opacity: 0.3 - now you can faintly see B
  • Remove the hidden-display class from Item B in section 4 - watch it reappear and push C over
  • Try adding display: none to Item A in any section - see how the layout shifts

Challenge

Create a page that demonstrates all three hiding methods in a real-world scenario:

  • Create three product cards side by side
  • Add a "SOLD OUT" label on one card using opacity: 0.4 to dim the entire card
  • Use visibility: hidden to hide the price on another card (but keep the space reserved)
  • Use display: none to completely remove a "delete" button from the third card
  • Add a note below each card explaining which method you used and why

What You Learned

  • opacity controls transparency from 0 (invisible) to 1 (fully visible) - affects the entire element and children
  • visibility: hidden makes an element invisible but it still takes up space in the layout
  • display: none completely removes an element from the layout - no space reserved
  • opacity can be animated with CSS transitions - perfect for fade effects
  • opacity: 0 elements are still clickable, while visibility: hidden elements are not
  • Use rgba() instead of opacity when you only want a transparent background without affecting children
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Display Property

The Simple Version

Every HTML element has a default display behavior. Some elements take up the full width of the page and stack on top of each other (like <div>, <p>, <h1>). Others flow side by side within text (like <span>, <a>, <strong>). The display property lets you change this behavior.

The four most common display values:

  • block - takes full width, stacks vertically. Like a shipping container on a cargo ship - each one sits on its own row.
  • inline - flows with text, side by side. You cannot set width or height on it.
  • inline-block - flows with text like inline, but you can set width and height.
  • none - completely removes the element from the page, as if it does not exist.
Block elements are like shipping containers (makontena) stacked one on top of another at Mombasa port - each one takes the full width of the ship. Inline elements are like words in a sentence - they flow next to each other on the same line.

What's Really Happening

The browser assigns a default display value to every element. Elements like <div>, <h1>-<h6>, <p>, <ul>, and <section> are block-level by default. Elements like <span>, <a>, <strong>, and <em> are inline by default.

Block elements:

  • Start on a new line
  • Take up the full available width
  • Respect width, height, margin, and padding on all sides

Inline elements:

  • Stay on the same line as surrounding content
  • Only take up as much width as their content needs
  • Ignore width and height
  • Only respect horizontal margin and padding (left/right), not vertical

Inline-block is the best of both worlds: it flows inline like text but accepts width, height, and vertical margin/padding.

Good to know: display: none removes the element completely - it takes up no space at all. This is different from visibility: hidden, which hides the element but still reserves its space on the page.

Try It Yourself

See how block, inline, and inline-block elements behave differently. Notice that inline elements ignore width and height.

HTML/CSS Code
Result

Things to try:

  • Remove the width from .block-example - it will stretch to fill the full width
  • Change .inline-example to display: inline-block and see the width/height take effect
  • Add display: none to .block-example - they all disappear!

Try More

A practical example: building a horizontal navigation menu using inline-block. This is how many navigation bars work.

HTML/CSS Code
Result

Challenge

Build a simple product listing page for a Kenyan market:

  • Create a horizontal navigation bar using display: inline-block on the links
  • Display at least 4 product cards side by side using inline-block
  • Add a "sold out" badge on one card and use display: none to hide it when needed
  • Use display: inline on a span inside each card for the price tag
  • Make sure your cards have a fixed width and height

What You Learned

  • display: block makes elements stack vertically and take full width
  • display: inline makes elements flow side by side like text, ignoring width/height
  • display: inline-block flows inline but respects width and height
  • display: none removes the element from the page completely
  • Block elements: <div>, <p>, <h1>-<h6>, <ul>, <section>
  • Inline elements: <span>, <a>, <strong>, <em>
  • display: none vs visibility: hidden - none removes space, hidden keeps it
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Width & Height

The Simple Version

CSS lets you control how wide and how tall an element is with width and height. You can use fixed sizes (pixels) or flexible sizes (percentages). You also have min-width, max-width, min-height, and max-height to set limits.

Think of it like building a matatu: You decide how wide the seats are (fixed width), but the route can stretch as long as needed (flexible height). Seat width is fixed, but the journey can be long or short.

What's Really Happening

Fixed Sizes

.box {
  width: 300px;
  height: 150px;
}

Percentage Sizes

Percentages are relative to the parent element:

.container { width: 800px; }
.half      { width: 50%; }  /* 400px  -  half of parent */

min- and max- constraints

.card {
  width: 100%;       /* fills parent */
  max-width: 600px;  /* but never wider than 600px */
  min-height: 100px; /* always at least 100px tall */
}

auto

width: auto (the default) lets the browser calculate the width. For block elements it fills the parent. For inline elements it shrinks to fit content.

Tip: Use max-width instead of fixed width for responsive layouts. A card with max-width: 500px; width: 100%; is full-width on mobile but capped on desktop.

Try It Yourself

HTML/CSS Code
Result

Things to try:

  • Change width: 60% to width: 100% - what happens?
  • Add min-width: 300px to the percent box
  • Remove height: 100px from the fixed box and add more text inside - height grows automatically

Challenge

Build a Nairobi tourist info card layout:

  • A header bar that is 100% wide with a max-width of 700px
  • Three info cards side by side, each exactly 200px wide and 150px tall
  • A footer that fills full width with a minimum height of 60px

What You Learned

  • width and height set fixed sizes in pixels
  • Percentages are relative to the parent element
  • max-width caps the size - great for responsive layouts
  • min-height ensures a minimum size even with little content
  • auto lets the browser decide (default behavior)
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Overflow

The Simple Version

When content is bigger than its container, CSS overflow controls what happens: does it spill out, get hidden, or show a scrollbar?

Think of a sufuria (cooking pot): If you fill it too much, the food overflows. You can choose to let it spill (visible), cut off the excess (hidden), or add a lid that lets you peek inside (scroll).

What's Really Happening

overflow: visible (default)

Content spills outside the box. The box stays the same size but content shows outside it.

.box { width: 150px; height: 80px; overflow: visible; }

overflow: hidden

Content that goes beyond the box is clipped - you won't see it at all.

.box { width: 150px; height: 80px; overflow: hidden; }

overflow: scroll

Always shows scrollbars (even if not needed).

.box { width: 150px; height: 80px; overflow: scroll; }

overflow: auto

Only shows scrollbars when content actually overflows. This is usually what you want.

.box { width: 150px; height: 80px; overflow: auto; }
overflow-x and overflow-y: You can control horizontal and vertical overflow separately:
overflow-x: hidden; - hide horizontal overflow only
overflow-y: auto; - scrollbar only when content is too tall

Try It Yourself

HTML/CSS Code
Result

Things to try:

  • Increase the box height to 200px - does overflow disappear?
  • Change overflow: auto to overflow: scroll - notice scrollbars always appear
  • Add overflow-x: hidden; overflow-y: auto; to one box

Challenge

Build a "Mombasa Beach News" scrollable feed:

  • A fixed-height container (300px) with overflow: auto
  • Fill it with 6+ news articles about Mombasa
  • Add a sidebar with overflow: hidden that clips a long title

What You Learned

  • overflow: visible - content spills out (default)
  • overflow: hidden - clips content at box edge
  • overflow: scroll - always shows scrollbars
  • overflow: auto - scrollbars only when needed (best choice)
  • Use overflow-x and overflow-y to control each axis separately
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Position

The Simple Version

The CSS position property controls how an element is placed on the page. There are five values: static, relative, absolute, fixed, and sticky. Once positioned, you use top, right, bottom, left to move it.

Think of market stalls in Gikomba: Most stalls are in their normal flow (static). Some are slightly shifted from where they'd normally be (relative). Some float above the crowd on a platform (absolute). And a market announcer who stays visible even as you walk past (fixed). Everything has its place.

What's Really Happening

static (default)

Normal document flow. top/left/right/bottom have no effect.

relative

Moved relative to where it would normally be. The original space is still reserved.

.box { position: relative; top: 10px; left: 20px; }

absolute

Removed from normal flow. Positioned relative to the nearest non-static ancestor (or the page if none).

.parent { position: relative; }
.child  { position: absolute; top: 0; right: 0; }

fixed

Stays in place relative to the browser window even when you scroll.

.navbar { position: fixed; top: 0; left: 0; width: 100%; }

sticky

Acts like relative until you scroll past a threshold, then sticks like fixed.

.section-header { position: sticky; top: 0; }

Try It Yourself

HTML/CSS Code
Result

Things to try:

  • Change top: 10px; right: 10px; on the absolute box to bottom: 10px; left: 10px;
  • Remove position: relative from the container - where does the absolute box go?
  • Add a new element with position: fixed; bottom: 20px; right: 20px; - it stays on screen while scrolling

Challenge

Build a Kenyan news card with a badge:

  • A card div with position: relative
  • A "BREAKING" badge absolutely positioned in the top-left corner
  • A category label absolutely positioned in the bottom-right
  • A fixed "Back to Top" button in the bottom-right of the screen

What You Learned

  • static - normal flow (default)
  • relative - shifted from its normal position; original space preserved
  • absolute - positioned relative to nearest non-static ancestor; removed from flow
  • fixed - stays fixed to the viewport when scrolling
  • sticky - relative until scroll threshold, then fixed
  • Use top, right, bottom, left to offset positioned elements
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Float & Clear

The Simple Version

float pushes an element to the left or right, allowing text and other elements to wrap around it. clear stops elements from wrapping around floated elements.

Think of a photo in a newspaper like Daily Nation: The photo floats to the right, and the article text wraps around it naturally. clear is like a caption that says "stop wrapping - I go below the photo".

What's Really Happening

float: left / right

img { float: right; margin-left: 15px; }
/* Text in the same container wraps around the image */

clear

.caption { clear: right; }
/* This element drops below the right-floated image */

footer { clear: both; }
/* This element drops below ALL floated elements */

The Clearfix Problem

If all children of a container are floated, the container collapses to zero height. Fix with the clearfix hack:

.container::after {
  content: "";
  display: block;
  clear: both;
}
Modern note: Floats were the main layout tool before Flexbox and Grid. Today, use float mainly for wrapping text around images. For layout, use Flexbox (lesson 28) or Grid (lesson 34).

Try It Yourself

HTML/CSS Code
Result

Things to try:

  • Change float: right to float: left - text wraps on the other side
  • Remove clear: right from the caption - what happens?
  • Remove clear: both from footer - the footer jumps up

Challenge

Create a Kenyan newspaper article layout:

  • Float an image left with text wrapping around it on the right
  • Float a pull-quote box to the right mid-article
  • Use clear: both before the footer
  • Apply the clearfix to the article container

What You Learned

  • float: left / float: right - makes elements float to one side
  • Text and inline content wraps around floated elements
  • clear: left/right/both - stops wrapping and drops below floats
  • The clearfix (::after trick) fixes collapsed containers
  • Use floats for text-wrapping images; use Flexbox/Grid for layout
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Introduction to Flexbox

The Simple Version

Flexbox (Flexible Box Layout) is a CSS layout system that makes it easy to arrange items in a row or column, space them out, and align them - all without the headaches of floats and inline-block hacks. Before Flexbox, centering something vertically was a nightmare. With Flexbox, it takes two lines.

With Flexbox, you have two key roles: the flex container (the parent that gets display: flex) and the flex items (the direct children inside it). The container controls the layout; the items respond to it.

Flexbox also introduces two axes: the main axis (the direction items flow - left to right by default) and the cross axis (perpendicular to the main axis - top to bottom by default).

Think of it like this: Flexbox is like arranging passengers in a matatu. The driver (the flex container) decides the direction of travel and how much space between seats. The passengers (flex items) sit in order and adjust based on the driver's rules. If the matatu goes left to right, that is the main axis. Top to bottom is the cross axis.

What's Really Happening

When you set display: flex on a container, several things happen immediately:

  • All direct children become flex items and line up in a row (by default)
  • Items no longer behave like block elements - they only take up as much width as they need
  • The main axis runs horizontally (left to right) by default
  • The cross axis runs vertically (top to bottom) by default
  • Items stretch to fill the container's height on the cross axis (by default)
Why Flexbox was created: Before Flexbox, developers used floats, inline-block, tables, and absolute positioning to create layouts. These were never designed for layout purposes and caused countless problems - clearing floats, dealing with whitespace gaps in inline-block, and the infamous "how do I vertically center this" question. Flexbox was specifically designed for one-dimensional layouts (a row OR a column at a time) and solves all these problems elegantly.

Remember: display: flex goes on the parent (container), not the children. The children automatically become flex items. You do not need to add any class or property to the children for them to participate in the flex layout.

Try It Yourself

See the difference between normal block layout and Flexbox. The boxes below use display: flex on the container to line items up in a row.

HTML/CSS Code
Result

Things to try:

  • Remove display: flex; from .flex-container - the green boxes will stack vertically like the red ones
  • Change gap: 10px to gap: 30px to add more space between items
  • Add more <div class="box"> elements inside the flex container

Try More

This example shows the main axis and cross axis visually. The colored boxes are flex items - they flow along the main axis and stretch along the cross axis.

HTML/CSS Code
Result

Things to try:

  • Change the container height from 200px to 100px or 300px - notice items stretch to match
  • Add a 5th item: <div class="item" style="background:#9b59b6; min-width:80px;">5</div>
  • Remove display: flex and see everything collapse to block layout

Challenge

Create a simple profile card row: use a flex container to place three profile cards side by side. Each card should have a colored background, a name, and a short description. Give the container a gap of 20px.

  • Make the container use display: flex
  • Give each card a different background color
  • Add padding and border-radius to make them look nice

What You Learned

  • Flexbox is a CSS layout system designed for arranging items in rows or columns
  • display: flex goes on the parent container - children become flex items automatically
  • By default, flex items line up in a row (left to right)
  • The main axis is the direction items flow; the cross axis is perpendicular to it
  • Flex items stretch to fill the container on the cross axis by default
  • The gap property adds space between flex items without using margins
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Flex Direction & Wrap

The Simple Version

flex-direction controls which way flex items flow - in a row (left to right) or a column (top to bottom). flex-wrap controls whether items stay on one line or wrap to the next.

Think of passengers boarding a matatu: They can line up in a row (row direction) or queue single-file (column direction). If the matatu is full, they wrap to a second queue (flex-wrap).

What's Really Happening

flex-direction

.container { display: flex; }

/* Default: items in a row, left to right */
flex-direction: row;

/* Items in a row, right to left */
flex-direction: row-reverse;

/* Items in a column, top to bottom */
flex-direction: column;

/* Items in a column, bottom to top */
flex-direction: column-reverse;

flex-wrap

/* Default: all items stay on one line (may shrink) */
flex-wrap: nowrap;

/* Items wrap to next line when they don't fit */
flex-wrap: wrap;

/* Items wrap to previous line */
flex-wrap: wrap-reverse;

flex-flow shorthand

/* flex-flow: direction wrap */
flex-flow: row wrap;
flex-flow: column nowrap;

Try It Yourself

Experiment with flex-direction and flex-wrap to see how they change the layout of items in a flex container.

HTML/CSS Code
Result

Things to try:

  • Change flex-direction: row to row-reverse - cities appear right to left
  • Change flex-wrap: wrap to nowrap - all items squeeze on one line
  • Change flex-direction: column to column-reverse - food list flips

Challenge

Build a Kenyan market stall layout:

  • A horizontal row of product tags that wraps when the screen is narrow
  • A vertical menu list using flex-direction: column
  • Use flex-flow shorthand on at least one container

What You Learned

  • flex-direction: row - items flow left to right (default)
  • flex-direction: column - items flow top to bottom
  • flex-direction: row-reverse / column-reverse - reversed directions
  • flex-wrap: wrap - items wrap to next line when needed
  • flex-wrap: nowrap - all items stay on one line (default)
  • flex-flow is shorthand for direction + wrap
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Justify Content

The Simple Version

justify-content aligns flex items along the main axis (horizontal in a row, vertical in a column). It distributes the empty space in the container.

Think of arranging mkate (bread) on a serving tray: You can push all the bread to one side, center it, spread it out evenly, or place equal space between each piece.

What's Really Happening

.container { display: flex; }

justify-content: flex-start;    /* items at start (default) */
justify-content: flex-end;      /* items at end */
justify-content: center;        /* items in center */
justify-content: space-between; /* equal space BETWEEN items */
justify-content: space-around;  /* equal space AROUND items */
justify-content: space-evenly;  /* perfectly equal space everywhere */
Visual reminder:
space-between: |item    item    item|
space-around: | item   item   item |
space-evenly: | item  item  item |

Try It Yourself

See how each justify-content value positions items differently inside the same container width.

HTML/CSS Code
Result

Things to try:

  • Add a 4th city to the space-between row - spacing adjusts automatically
  • Change the container width with max-width: 400px on .row to see the effect more clearly
  • Try flex-direction: column - justify-content now works vertically

Challenge

Build a Kenyan restaurant nav bar:

  • Logo on the left, nav links centered, a "Book Table" button on the right - use space-between
  • A footer with social media icons using space-evenly
  • A pricing section with 3 plan cards using space-around

What You Learned

  • flex-start - all items at the start (default)
  • flex-end - all items at the end
  • center - all items in the center
  • space-between - space between items, none at edges
  • space-around - space around each item (half at edges)
  • space-evenly - perfectly equal space everywhere
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Align Items & Content

The Simple Version

align-items aligns flex items along the cross axis (vertical when direction is row). align-content does the same but for multiple rows/columns. Together with justify-content, you can center anything perfectly.

Think of arranging fruits at a Nairobi market stall: justify-content controls left-right spacing. align-items controls how tall items line up vertically - do the mangoes sit at the top, middle, or bottom of the shelf?

What's Really Happening

align-items (single row)

.container { display: flex; height: 200px; }

align-items: stretch;     /* items stretch to fill container height (default) */
align-items: flex-start;  /* items align to top */
align-items: flex-end;    /* items align to bottom */
align-items: center;      /* items align to vertical center */
align-items: baseline;    /* items align by text baseline */

Perfect centering trick

.center-everything {
  display: flex;
  justify-content: center; /* horizontal center */
  align-items: center;     /* vertical center */
}

align-content (multiple rows)

Only works when flex-wrap: wrap creates multiple lines:

align-content: flex-start;
align-content: center;
align-content: space-between;
align-content: space-around;

Try It Yourself

See how different align-items values change how items line up. Kenyan cities - Nairobi, Mombasa, Kisumu - are arranged differently!

HTML/CSS Code
Result

Things to try:

  • Change align-items: stretch on a row - items grow to fill the 100px height
  • Add align-self: flex-start to a single item inside a center-aligned row
  • Try making a perfectly centered modal using the hero technique

Challenge

Build a Kenyan airline booking card:

  • A flex row with a flight icon, departure city, arrow, arrival city - all vertically centered
  • A hero banner that perfectly centers "Book Your Safari Flight" text both horizontally and vertically
  • Use align-self to push the price tag to the bottom of a card

What You Learned

  • align-items - aligns items on the cross axis (vertical for row direction)
  • stretch - items fill container height (default)
  • flex-start / flex-end / center - top, bottom, or middle
  • justify-content: center + align-items: center = perfect centering
  • align-self - overrides align-items for a single item
  • align-content - for multiple rows (needs flex-wrap: wrap)
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Flex Grow, Shrink & Basis

The Simple Version

These three properties control how a flex item sizes itself relative to other items. flex-basis sets the starting size. flex-grow controls how much it can expand. flex-shrink controls how much it can compress. The shorthand flex combines all three.

Think of land allocation in a shamba (farm): Each farmer starts with a base plot (flex-basis). When there's extra land, bigger families get more (flex-grow ratio). When land is scarce, who gives up the most? (flex-shrink). Every farmer has a base plot, but it can grow or shrink.

What's Really Happening

flex-basis

The initial size of the item before distributing free space:

.item { flex-basis: 200px; }  /* starts at 200px */
.item { flex-basis: auto; }   /* uses width/height (default) */
.item { flex-basis: 0; }      /* starts at zero, grows from nothing */

flex-grow

How much of the remaining space the item takes, as a ratio:

.sidebar { flex-grow: 1; } /* takes 1 share of free space */
.main    { flex-grow: 3; } /* takes 3 shares  -  3x bigger than sidebar */

flex-shrink

How much the item shrinks when there isn't enough space (default: 1):

.important { flex-shrink: 0; } /* never shrinks */
.normal    { flex-shrink: 1; } /* shrinks normally (default) */

flex shorthand

/* flex: grow shrink basis */
.item  { flex: 1; }         /* flex: 1 1 0%  -  equal sizing */
.item  { flex: 2 1 200px; } /* starts at 200px, grows 2x as fast */
.fixed { flex: 0 0 200px; } /* never grows or shrinks, always 200px */

Try It Yourself

See flex-grow, flex-shrink, and flex-basis in action. The sidebar has a fixed size while the main content takes all remaining space!

HTML/CSS Code
Result

Things to try:

  • Change sidebar to flex: 1 - it now grows like the main content
  • Change the ratio row to 1, 3, 1 - the middle gets even larger
  • Add flex-shrink: 0 to one equal column - it won't shrink when space is tight

Challenge

Build a Kenyan news site layout:

  • A fixed-width logo column (flex: 0 0 80px)
  • A growing search bar (flex: 1)
  • A fixed nav button area (flex: 0 0 150px)
  • A 2:1 content+sidebar layout below

What You Learned

  • flex-basis - starting size of a flex item
  • flex-grow - how much it expands (0 = never, 1+ = proportional)
  • flex-shrink - how much it shrinks (0 = never, default 1)
  • flex: 1 - shorthand for equal, flexible columns
  • flex: 0 0 200px - fixed size, never changes
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Flexbox Patterns

The Simple Version

Now that you know all the flexbox properties, here are the most common real-world patterns you'll use over and over. These are the building blocks of modern web layouts.

Common Patterns

Four essential flexbox patterns used in almost every website - demonstrated with a Kenyan travel theme.

HTML/CSS Code
Result

Patterns used:

  • Navbar: space-between + align-items: center
  • Card grid: flex-wrap: wrap + flex: 1 1 200px
  • Media object: flex: 0 0 40px icon + flex: 1 content
  • Sticky footer: flex-direction: column + flex: 1 on content

Challenge

Build a complete Kenyan restaurant website page using all four flexbox patterns:

  • Navbar: logo left, menu center, "Order Now" button right
  • Menu card grid: dishes that wrap responsively
  • Reviews section using the media object pattern (avatar + review text)
  • Sticky footer at the bottom

What You Learned

  • Navbar pattern: flexbox row + space-between + align-items center
  • Card grid: flex-wrap + flex-basis for responsive cards
  • Media object: fixed icon + flexible content area
  • Sticky footer: column direction + flex: 1 on main content
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Introduction to CSS Grid

The Simple Version

CSS Grid lets you create two-dimensional layouts - rows and columns at the same time. While Flexbox handles one axis at a time, Grid handles both simultaneously. It's the most powerful layout system in CSS.

Think of a shamba plot divided by paths: You draw lines across (rows) and lines down (columns), creating a grid of plots. Each crop (element) can be placed in any plot, and some crops can span multiple plots.

What's Really Happening

Enabling Grid

.container { display: grid; }

Defining Columns and Rows

.container {
  display: grid;
  grid-template-columns: 200px 200px 200px; /* 3 columns, 200px each */
  grid-template-rows: 100px 100px;           /* 2 rows, 100px each */
}

The fr unit

fr means "fraction of available space" - like flex: 1 but for grid:

grid-template-columns: 1fr 1fr 1fr;   /* 3 equal columns */
grid-template-columns: 2fr 1fr;       /* 2 columns, first is twice as wide */

repeat()

grid-template-columns: repeat(3, 1fr); /* same as 1fr 1fr 1fr */
grid-template-columns: repeat(4, 200px); /* 4 columns of 200px */
Grid vs Flexbox:
Use Flexbox for one-dimensional layouts (a row of items, a column of items).
Use Grid for two-dimensional layouts (rows AND columns at the same time).

Try It Yourself

Experiment with grid columns below. See how fr units divide space proportionally.

HTML/CSS Code
Result

Things to try:

  • Change repeat(3, 1fr) to repeat(4, 1fr) - now 4 columns
  • Change 2fr 1fr to 1fr 1fr 1fr - three equal columns
  • Add grid-template-rows: 100px to fix row heights

Challenge

Build a Kenyan nature photo gallery grid:

  • 4-column grid for photos using repeat(4, 1fr)
  • Each "photo" is a colored box with the animal/place name
  • Include at least 8 items: lion, elephant, giraffe, Mara river, Mount Kenya, flamingos, zebra, cheetah

What You Learned

  • display: grid enables CSS Grid on a container
  • grid-template-columns defines column sizes
  • grid-template-rows defines row sizes
  • fr unit = fraction of available space
  • repeat(n, size) is shorthand for repeating column/row definitions
  • Grid handles two dimensions; Flexbox handles one
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Grid Template

The Simple Version

Grid items can span multiple columns or rows using grid-column and grid-row. You tell an item where to start and where to end using grid line numbers. This lets you build complex layouts like magazine pages.

Think of a Kenyan newspaper layout: The headline story spans all 4 columns. Two medium stories span 2 columns each. Smaller stories fit in single columns. You're placing content on a pre-drawn grid.

What's Really Happening

Grid lines

Grid lines are numbered from 1. A 3-column grid has lines 1, 2, 3, 4 (4 lines for 3 columns).

Placing items

/* Span from line 1 to line 3 = 2 columns wide */
.header { grid-column: 1 / 3; }

/* Span from line 1 to line 4 = full width (3 columns) */
.hero { grid-column: 1 / 4; }

/* Shorthand: start / span how-many */
.sidebar { grid-column: 3 / span 1; }

/* Row spanning */
.tall-item { grid-row: 1 / 3; } /* spans 2 rows */

Negative line numbers

/* -1 means the last line */
.full-width { grid-column: 1 / -1; } /* always spans full width */

Try It Yourself

See how items can span multiple columns and rows to create a newspaper-style layout.

HTML/CSS Code
Result

Things to try:

  • Change grid-column: 1 / -1 to grid-column: 1 / 3 - headline only spans half
  • Add grid-column: span 3 to a small item
  • Change grid-row: span 2 to grid-row: span 3

Challenge

Build a Kenya magazine layout with a 3-column grid:

  • A hero image spanning all 3 columns
  • A main article spanning 2 columns
  • A sidebar spanning 1 column and 2 rows
  • Three small articles in the remaining space

What You Learned

  • Grid lines are numbered from 1 (and -1 from the end)
  • grid-column: 1 / 3 - item starts at line 1, ends at line 3
  • grid-column: span 2 - item spans 2 columns from wherever it is
  • grid-column: 1 / -1 - item spans full width
  • grid-row works the same way but for rows
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Grid Gap & Areas

The Simple Version

gap adds space between grid cells. grid-template-areas lets you name regions of your grid and place items by name - making layouts incredibly readable.

Think of a floor plan in an NHC apartment: You label each room - "bedroom", "kitchen", "living room" - and the builder knows exactly where everything goes. grid-template-areas does the same for web layouts.

What's Really Happening

gap

.grid { gap: 20px; }           /* 20px between all cells */
.grid { gap: 10px 20px; }     /* 10px rows, 20px columns */
.grid { row-gap: 10px; }      /* rows only */
.grid { column-gap: 20px; }   /* columns only */

grid-template-areas

.layout {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header  header"
    "sidebar main"
    "footer  footer";
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }

Use a . (dot) for empty cells:

grid-template-areas:
  "header header header"
  "sidebar main   .    "
  "footer  footer footer";

Try It Yourself

Build a complete page layout using named grid areas. Notice how readable the template string is!

HTML/CSS Code
Result

Things to try:

  • Change the sidebar column from 200px to 1fr - it becomes equal width with main
  • Change "sidebar main" to "main sidebar" - sidebar moves to the right
  • Increase gap: 8px to gap: 20px - wider gutters between sections

Challenge

Build a complete Kenyan government website layout using grid-template-areas:

  • Header, left nav, main content, right sidebar, footer
  • Header and footer span full width
  • Use named areas: "header", "nav", "main", "aside", "footer"

What You Learned

  • gap - space between grid cells
  • grid-template-areas - name regions with a visual map
  • grid-area: name - assign an item to a named region
  • Use . for empty areas in the template
  • Named areas make layouts easy to read and change
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Grid Alignment

The Simple Version

CSS Grid has alignment properties similar to Flexbox. justify-items and align-items control how items sit within their grid cells. justify-content and align-content control how the entire grid sits within its container.

What's Really Happening

Aligning items within their cells

.grid {
  /* Horizontal alignment within cells */
  justify-items: start | end | center | stretch;

  /* Vertical alignment within cells */
  align-items: start | end | center | stretch;
}

/* Override for a single item */
.item { justify-self: end; align-self: center; }

Aligning the whole grid

When the grid is smaller than its container:

.grid {
  justify-content: start | end | center | space-between | space-around;
  align-content: start | end | center | space-between | space-around;
}
Default is stretch: By default, grid items stretch to fill their entire cell. Setting justify-items: start makes items only as wide as their content.

Try It Yourself

Compare how different alignment values change how items sit inside their grid cells.

HTML/CSS Code
Result

Things to try:

  • Add justify-self: end; to a single .item - it overrides the grid-wide setting
  • Try align-items: end - all items sink to the bottom of their cells

Challenge

Build a Kenyan airline seat map:

  • A 6-column grid (3 + aisle + 3)
  • Seat labels centered in each cell
  • A wider "aisle" column using a fixed width
  • Business class seats with align-self: stretch

What You Learned

  • justify-items - horizontal alignment of items in their cells
  • align-items - vertical alignment of items in their cells
  • justify-self / align-self - override for a single item
  • justify-content / align-content - position the whole grid in its container
  • Default is stretch - items fill their cells
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Grid Patterns

The Simple Version

Here are the most common real-world CSS Grid patterns. Master these and you can build almost any website layout.

Common Grid Patterns

Three powerful patterns you'll use constantly: auto-responsive grids, the Holy Grail layout, and mixed tile sizes for magazine-style pages.

HTML/CSS Code
Result

Key techniques used:

  • repeat(auto-fill, minmax(120px, 1fr)) - responsive grid without media queries
  • grid-template-areas - readable Holy Grail layout
  • grid-row: span 2 / grid-column: span 2 - mixed tile sizes

Challenge

Build a complete Kenyan tourism website homepage using Grid:

  • Use the Holy Grail layout for the page structure
  • An auto-fill card grid for destinations
  • A featured destination using a large spanning tile

What You Learned

  • auto-fill + minmax() creates responsive grids without media queries
  • Named areas make page layouts readable and maintainable
  • Spanning items create magazine-style mixed layouts
  • grid-auto-rows sets a default row height for auto-created rows
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Media Queries

The Simple Version

Media queries let you apply CSS only when certain conditions are true - like when the screen is narrower than 768px. This is how you make sites look good on both phones and desktops.

Think of a kanga that changes pattern depending on who wears it: On a child, it looks one way; on an adult, it looks another. Media queries let your website change its look depending on the device.

What's Really Happening

Basic syntax

@media (max-width: 768px) {
  /* These styles only apply when screen is 768px or narrower */
  .sidebar { display: none; }
  .main    { width: 100%; }
}

Common breakpoints

/* Mobile: up to 480px */
@media (max-width: 480px) { ... }

/* Tablet: 481px to 768px */
@media (min-width: 481px) and (max-width: 768px) { ... }

/* Desktop: 769px and wider */
@media (min-width: 769px) { ... }

min-width vs max-width

max-width: 768px - applies when screen is smaller than 768px (mobile-first: add this for overrides)
min-width: 768px - applies when screen is larger than 768px (desktop-first: add this for overrides)

Always include the viewport meta tag in your HTML:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Without this, mobile browsers render at desktop width and then scale down.

Try It Yourself

Resize the preview panel to see the layout change.

HTML/CSS Code
Result

Things to try:

  • Change max-width: 500px to max-width: 800px - the mobile layout always shows
  • Add a media query that changes the background color on narrow screens
  • Hide the sidebar completely with display: none on mobile

Challenge

Build a responsive Kenyan news site:

  • 3-column layout on desktop
  • 2-column layout on tablets (max-width: 768px)
  • Single column on mobile (max-width: 480px)
  • Navigation collapses to a menu list on mobile

What You Learned

  • @media (max-width: Xpx) - apply styles when screen is narrower than X
  • @media (min-width: Xpx) - apply styles when screen is wider than X
  • Common breakpoints: 480px (mobile), 768px (tablet), 1024px (desktop)
  • Always include the viewport meta tag
  • Use and to combine conditions: (min-width: 481px) and (max-width: 768px)
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Responsive Units

The Simple Version

Instead of always using px (fixed pixels), CSS has units that scale with the screen or the font size. These make your layouts naturally responsive without always needing media queries.

Think of measuring in Kenya: A fixed measure is like saying "exactly 10 metres". A relative measure is like saying "half the distance to that tree" - it changes depending on where the tree is.

What's Really Happening

em - relative to parent font size

body { font-size: 16px; }
p    { font-size: 1em; }    /* 16px */
h1   { font-size: 2em; }    /* 32px */
.box { padding: 1.5em; }    /* 24px (1.5 × 16px) */

rem - relative to root font size

html { font-size: 16px; }
p    { font-size: 1rem; }   /* always 16px, ignores parent */
h1   { font-size: 2rem; }   /* always 32px */

vw and vh - relative to viewport

/* 1vw = 1% of viewport width */
.hero  { width: 100vw; }   /* full viewport width */
.banner { font-size: 5vw; } /* scales with screen width */

/* 1vh = 1% of viewport height */
.hero  { height: 100vh; }  /* full viewport height */
.half  { height: 50vh; }   /* half viewport height */

% - relative to parent

.container { width: 800px; }
.child     { width: 50%; }  /* 400px */
Best practice: Use rem for font sizes, px for borders/shadows, % or fr for layouts, vh/vw for full-screen sections.

Try It Yourself

Resize the preview panel to see how different units respond.

HTML/CSS Code
Result

Things to try:

  • Change 4vw to 8vw - heading becomes much larger
  • Change html { font-size: 16px } to 20px - all rem-based sizes scale up
  • Change height: 40vh to 100vh - hero fills full screen height

Challenge

Build a responsive Kenyan travel card component:

  • Use rem for all font sizes
  • Use em for padding (so it scales with font size)
  • Use vh for a full-screen hero section
  • Use % for a responsive image width

What You Learned

  • px - fixed pixels, always the same size
  • em - relative to parent's font size
  • rem - relative to root (html) font size - most predictable
  • vw / vh - percentage of viewport width/height
  • % - relative to parent element
  • Best practice: rem for fonts, % for layout, vh for full-screen sections
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Responsive Images

The Simple Version

Images by default don't resize with the screen - they keep their original size and can overflow the page. Making images responsive means they scale down on small screens but never get bigger than their natural size.

Think of a photo in a matatu window frame: The photo should fit the frame perfectly - not spill outside it, and not stretch beyond it. Images should never break their container.

What's Really Happening

The one rule you always need

img {
  max-width: 100%;
  height: auto;
}
/* Image never exceeds container width, keeps proportions */

object-fit for fixed-size image containers

.photo {
  width: 300px;
  height: 200px;
  overflow: hidden;
}

.photo img {
  width: 100%;
  height: 100%;
  object-fit: cover;   /* crops to fill, keeps ratio */
  object-fit: contain; /* fits inside, may show empty space */
  object-fit: fill;    /* stretches to fill (may distort) */
}

object-position

img {
  object-fit: cover;
  object-position: center top; /* focus on top of image */
  object-position: 30% 60%;   /* custom focal point */
}

Background images

.hero {
  background-image: url('photo.jpg');
  background-size: cover;     /* fill container */
  background-position: center;
  background-repeat: no-repeat;
  height: 400px;
}

Try It Yourself

Experiment with different image fitting techniques using colored boxes to simulate photos.

HTML/CSS Code
Result

Things to try:

  • Change max-width: 600px on the container to 300px - banner shrinks
  • Change background-size: cover to contain and observe the difference
  • Add background-position: top to the cover image

Challenge

Build a Kenya wildlife photo gallery:

  • 6 "photo cards" in a grid, each with a fixed 200×150px image area
  • Use colored gradient boxes to simulate lion, elephant, giraffe, zebra, cheetah, hippo photos
  • Each card uses object-fit: cover so images fill the frame
  • Cards are fully responsive - wrap on narrow screens

What You Learned

  • max-width: 100%; height: auto; - the one rule for responsive images
  • object-fit: cover - fills container, crops to fit
  • object-fit: contain - fits inside, may show empty space
  • object-position - controls focal point of cropped image
  • background-size: cover - same concept for background images
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Mobile-First Design

The Simple Version

Mobile-first means you write CSS for the smallest screen first, then use min-width media queries to add complexity for larger screens. This is the industry standard approach because most users are on mobile - especially in Kenya where smartphones dominate internet access.

Think of packing a bag for a safari: Pack only the essentials first (mobile). Once you know you have a vehicle with extra space (tablet, desktop), add the extras. You don't pack everything and then remove items - you start minimal.

What's Really Happening

Desktop-first (old approach)

/* Default: desktop layout */
.container { display: grid; grid-template-columns: 1fr 1fr 1fr; }

/* Override for mobile */
@media (max-width: 768px) {
  .container { grid-template-columns: 1fr; }
}

Mobile-first (modern approach)

/* Default: mobile layout */
.container { display: grid; grid-template-columns: 1fr; }

/* Enhance for tablet */
@media (min-width: 600px) {
  .container { grid-template-columns: 1fr 1fr; }
}

/* Enhance for desktop */
@media (min-width: 1024px) {
  .container { grid-template-columns: 1fr 1fr 1fr; }
}
Why mobile-first is better:
  • Forces you to focus on core content first
  • Smaller CSS for the most common device (mobile)
  • Easier to progressively enhance than to strip down
  • Kenya has 85%+ mobile internet usage

Try It Yourself

Resize the preview panel to see the 1-column to 2-column to 3-column transition in action.

HTML/CSS Code
Result

Things to try:

  • Resize the preview panel - see the 1→2→3 column transition
  • Change min-width: 600px to min-width: 400px - 2 columns come earlier
  • Add a 4th breakpoint at 1200px for 4 columns

Challenge

Build a complete mobile-first Kenyan food delivery app page:

  • Mobile: full-width cards, large touch-friendly buttons (min 44px)
  • Tablet: 2-column menu grid
  • Desktop: 3-column grid + sidebar showing cart
  • All transitions using min-width queries only

What You Learned

  • Mobile-first: write default CSS for mobile, enhance for larger screens
  • Use min-width media queries to progressively add features
  • Desktop-first (max-width) is the old approach - avoid for new projects
  • Kenya's mobile-heavy internet usage makes mobile-first even more important
  • Core content should work and look good with zero media queries
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

CSS Transitions

The Simple Version

CSS transitions make property changes animate smoothly instead of jumping instantly. When a button changes color on hover, a transition makes it fade rather than snap. You control which property animates, how long it takes, and the timing curve.

Think of sunrise over the Rift Valley: The sky doesn't jump from black to blue - it transitions gradually through orange, pink, and gold. CSS transitions do the same for your properties.

What's Really Happening

Basic syntax

/* transition: property duration timing-function delay */
.btn {
  background-color: #006600;
  transition: background-color 0.3s ease;
}

.btn:hover {
  background-color: #c0392b;
  /* Changes smoothly over 0.3 seconds */
}

Transitioning multiple properties

.card {
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

/* Or transition all properties */
.card { transition: all 0.3s ease; }

Timing functions

ease        /* slow start, fast middle, slow end (default) */
linear      /* constant speed */
ease-in     /* slow start, speeds up */
ease-out    /* fast start, slows down */
ease-in-out /* slow start and end */
What can be transitioned? Most properties with numeric values: color, opacity, width, height, padding, margin, transform, font-size, border-radius. NOT: display, visibility, content.

Try It Yourself

Hover over the elements to see transitions in action.

HTML/CSS Code
Result

Things to try:

  • Change 0.3s ease to 1s ease - very slow transition
  • Change ease to linear on the button - feels mechanical
  • Add transition-delay: 0.2s to the card - it waits before starting

Challenge

Build an interactive Kenyan safari booking button panel:

  • A "Book Safari" button that transitions color and grows on hover
  • Destination cards with a lift effect on hover
  • A menu that reveals a dropdown with an opacity transition
  • Price tags that change color when hovered

What You Learned

  • transition: property duration timing
  • Put transition on the element, not the :hover state
  • Common timing: 0.2s–0.4s for interactive elements
  • Timing functions: ease, linear, ease-in, ease-out, ease-in-out
  • transition: all 0.3s ease transitions every property at once
  • Only numeric/color properties can be transitioned
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

CSS Transforms

The Simple Version

CSS transform lets you move, rotate, scale, and skew elements without affecting the page layout. The element appears transformed but its original space is still reserved. Transforms are often combined with transitions for smooth effects.

Think of a Maasai warrior's spear: You can spin it (rotate), extend it (scale), move it (translate), or tilt it (skew) - but the warrior's hand stays in place. Change the shape without changing the space.

What's Really Happening

translate - move

transform: translateX(20px);         /* move right */
transform: translateY(-10px);        /* move up */
transform: translate(20px, -10px);   /* move right and up */
transform: translateX(-50%) translateY(-50%); /* centering trick */

rotate

transform: rotate(45deg);    /* 45 degrees clockwise */
transform: rotate(-90deg);   /* 90 degrees counter-clockwise */

scale

transform: scale(1.5);       /* 150% size */
transform: scale(0.8);       /* 80% size */
transform: scaleX(2);        /* double width only */

skew

transform: skewX(15deg);     /* slant horizontally */
transform: skewY(10deg);     /* slant vertically */

Combining transforms

transform: rotate(45deg) scale(1.2) translateX(10px);
transform-origin: Controls the pivot point for transforms (default: center).
transform-origin: top left; - rotates from the top-left corner.

Try It Yourself

Hover over each box to see the transform.

HTML/CSS Code
Result

Things to try:

  • Change rotate(15deg) to rotate(180deg) - box flips upside down
  • Change scale(1.2) to scale(0.5) - box shrinks
  • Add transition: transform 1s ease-in-out for very slow transforms

Challenge

Build interactive Kenyan flag cards:

  • 4 country flag cards (Kenya, Tanzania, Uganda, Rwanda) using colored backgrounds
  • Hover to flip each card: rotate(180deg) combined with scale
  • Use transform-origin: left center for a page-turn effect
  • All with smooth transition: transform 0.4s ease

What You Learned

  • translateX/Y() - move horizontally / vertically
  • rotate(deg) - spin an element
  • scale() - resize (1 = normal, 2 = double, 0.5 = half)
  • skewX/Y(deg) - slant an element
  • Combine transforms: transform: rotate(10deg) scale(1.1)
  • transform-origin sets the pivot point (default: center)
  • Transforms work great with transitions for smooth animation
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

CSS Animations

The Simple Version

CSS animations let elements animate automatically - no hover or click needed. You define keyframes (steps of the animation) with @keyframes, then apply the animation to an element. Unlike transitions which need a trigger, animations run on their own.

Think of a Kenyan ngoma dance performance: The dancers follow choreographed steps from beginning to end, repeating the routine. @keyframes is the choreography, and animation is the instruction to perform it.

What's Really Happening

Defining keyframes

@keyframes slideIn {
  from { opacity: 0; transform: translateY(-20px); }
  to   { opacity: 1; transform: translateY(0); }
}

/* Or with percentages for more control */
@keyframes pulse {
  0%   { transform: scale(1); }
  50%  { transform: scale(1.1); }
  100% { transform: scale(1); }
}

Applying the animation

/* animation: name duration timing iteration direction fill-mode */
.box {
  animation: slideIn 0.5s ease forwards;
  animation: pulse 2s ease-in-out infinite;
}

Key properties

animation-name: slideIn;
animation-duration: 1s;
animation-timing-function: ease;
animation-delay: 0.3s;         /* wait before starting */
animation-iteration-count: 3;  /* or: infinite */
animation-direction: alternate; /* reverses on even iterations */
animation-fill-mode: forwards;  /* keeps final state after finishing */

Try It Yourself

Watch the animations run automatically on page load.

HTML/CSS Code
Result

Things to try:

  • Change infinite to 3 on the bounce - it stops after 3 bounces
  • Add animation-direction: alternate to colorCycle - smoother transitions
  • Increase animation-delay gaps to 0.5s on the cards

Challenge

Build an animated Kenyan flag (using CSS shapes):

  • Three horizontal stripes (black, red, green) using a grid
  • A white circle in the center that pulses
  • The whole flag fades in with fadeInDown on page load
  • On hover, the flag slowly rotates using a @keyframes rotate

What You Learned

  • @keyframes name { from {} to {} } - defines animation steps
  • animation: name duration timing count - applies the animation
  • infinite - loops forever
  • animation-delay - staggers multiple animations
  • animation-fill-mode: forwards - keeps final state
  • animation-direction: alternate - reverses on even runs
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

CSS Filters

The Simple Version

CSS filter applies visual effects to elements - like photo editing tools built into CSS. You can blur, brighten, add contrast, convert to grayscale, rotate hue, and more. Works great on images and can be animated with transitions.

Think of Instagram filters on a photo of Kilimanjaro: You can make it black & white, increase the contrast, add a warm glow, or blur the background. CSS filters do the same directly in your code - change photo effects without opening any editing software.

What's Really Happening

filter: blur(4px);            /* blur the element */
filter: brightness(1.5);      /* 150% brightness (1 = normal) */
filter: contrast(2);          /* 200% contrast */
filter: grayscale(100%);      /* full black & white */
filter: grayscale(0%);        /* full color (default) */
filter: sepia(80%);           /* old photograph effect */
filter: hue-rotate(90deg);    /* rotate all colors by 90° */
filter: invert(100%);         /* invert all colors */
filter: saturate(2);          /* 200% color saturation */
filter: opacity(0.5);         /* 50% transparent (like opacity) */
filter: drop-shadow(2px 4px 6px rgba(0,0,0,0.5)); /* shadow */

/* Combine multiple filters */
filter: brightness(1.2) contrast(1.1) saturate(1.3);
backdrop-filter: Applies the filter to whatever is behind the element - great for frosted glass effects:
.glass { background: rgba(255,255,255,0.2); backdrop-filter: blur(10px); }

Try It Yourself

Hover over each photo card to see the filter effect. Each card shows a different CSS filter in action.

HTML/CSS Code
Result

Things to try:

  • Add filter: hue-rotate(180deg) to one card on hover - colors completely shift
  • Try combining: filter: grayscale(100%) brightness(1.5)
  • Change backdrop-filter: blur(8px) to blur(20px) for stronger frosted glass

Challenge

Build a Kenyan wildlife photo gallery with filter effects:

  • 6 photo cards using colorful gradients (simulate wildlife photos)
  • Default: all cards in grayscale
  • Hover: each card reveals color with grayscale(0%) + slight brightness boost
  • A smooth transition: filter 0.5s ease
  • A caption overlay with frosted glass using backdrop-filter

What You Learned

  • filter: grayscale() - black & white (0% = color, 100% = b&w)
  • filter: blur() - blurs the element
  • filter: brightness() - 1 = normal, >1 = brighter, <1 = darker
  • filter: sepia() - vintage photograph look
  • filter: invert() - flip all colors
  • filter: hue-rotate() - shift all colors around the color wheel
  • backdrop-filter - filters whatever is behind the element
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

Final Project: Build a Complete Styled Website

Congratulations!

You have completed all 47 lessons of the CSS course. You now know everything needed to style a professional, responsive, animated website. This final project brings it all together.

This is your graduation ceremony. Like finishing secondary school at a top Kenyan school - you've built the foundation. Now it's time to prove it. Build something real. Build something you're proud of. You can do this!

Project: Kenya Tourism Website

Build a complete, styled, responsive tourism website for Kenya using all the CSS skills you've learned.

Requirements Checklist

Module 1-2: Basics & Text
  • Use CSS variables for your color palette
  • Custom font using Google Fonts
  • Proper line-height and letter-spacing for readability
  • Comments to document your code sections
Module 3-4: Box Model & Backgrounds
  • Use box-sizing: border-box globally
  • Cards with padding, margin, border, and border-radius
  • A hero section with a gradient background
  • Box shadows on cards
Module 5: Layout Basics
  • Position a badge/label absolutely on a card
  • A fixed navigation bar that stays at the top
  • z-index to keep nav above content
Module 6: Flexbox
  • Flexbox navbar with logo left and links right
  • A features/benefits section using flex
  • Perfectly centered hero text using flexbox
Module 7: CSS Grid
  • A destination card grid using auto-fill + minmax
  • A featured destination that spans 2 columns
  • A footer with a 3 or 4 column grid layout
Module 8: Responsive Design
  • Mobile-first approach using min-width media queries
  • Single column on mobile, multi-column on desktop
  • Responsive hero text using clamp() or vw units
Module 9: Effects
  • Transition on all interactive elements (hover, focus)
  • Card lift effect on hover using transform + box-shadow
  • At least one CSS animation (loading indicator, fade-in, etc.)
  • Filter effect on images (grayscale to color on hover)

Starter Template

Here's a complete starter. Extend it to meet all the requirements above.

HTML/CSS Code
Result

What to Add Next

The starter covers the core structure. Now extend it:

  • Add a testimonials section with a grid of review cards
  • Add a "How It Works" section with 3 flex items and icons
  • Add a loading animation that fades out after 1 second
  • Make the nav links turn orange on scroll (you'll need a little JavaScript - perfect next step)
  • Add a booking form with styled inputs and validation states

What's Next: JavaScript

You can now style anything. But CSS alone can't respond to user interactions in complex ways - clicking, fetching data, showing/hiding content dynamically. That's where JavaScript comes in. JavaScript is the third pillar of web development alongside HTML and CSS. It's coming soon to Code Hub.

You've Completed the CSS Course!

  • 47 lessons across 10 modules
  • CSS basics, selectors, colors, text, fonts
  • The box model: padding, borders, margin
  • Backgrounds, gradients, shadows, opacity
  • Layout: display, width/height, overflow, position, float, z-index
  • Flexbox: direction, wrap, justify, align, grow/shrink
  • CSS Grid: template, spanning, areas, alignment
  • Responsive design: media queries, units, images, mobile-first
  • Effects: transitions, transforms, animations, filters

Congratulations! You've completed the CSS course.

/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();
Questions while you work through the steps? The Course Coach (bottom right) knows this course inside out.
Browse more courses →
Ask the coachAI guide for this course