HTML & CSS how-to
Short ready-made solutions to common HTML & CSS tasks with code examples.
Layout and alignment
- How to align an item to the rightRight alignment in CSS: margin-left auto in flexbox, justify-content flex-end and text-align right for text.
- How to center an elementCentering in CSS: horizontally and vertically with flexbox and grid, a block with margin auto and text with text-align.
- How to make a full-height sectionA section as tall as the browser window: the vh, dvh and svh units and why min-height beats height.
- How to make a masonry layoutCards of different heights without gaps: multi-column layout with columns and break-inside, and the state of grid masonry.
- How to make a page layout with gridThe classic holy grail layout: a header, two side columns, the content and a footer with grid-template-areas.
- How to make a sidebar layoutA fixed-width sidebar next to the main content with grid, moving above it on a phone.
- How to make a sticky headerA header that stays at the top while scrolling: position sticky, top 0 and a background so the content does not show through.
- How to make equal-height columnsColumns and cards of the same height with different amounts of text: flexbox and grid stretch them by themselves.
- How to make two columnsTwo columns in CSS: equal and unequal with grid or flexbox, collapsing into one on a phone.
- How to overlap elementsOverlapping elements in CSS: a caption over an image with position absolute and stacking in one grid cell.
- How to place an element in a cornerA badge, a close button or a label in the corner of a card: position absolute with top and right inside a relative parent.
- How to push the footer to the bottomA footer at the bottom of the screen even on a short page: a flexbox column with min-height 100vh and a growing main.
- How to put items side by sideBlocks on one line: display flex on the parent, wrapping with flex-wrap and lining up an image with text.
- How to space items evenlyEqual spacing between items in a row: justify-content space-between, space-around, space-evenly and gap.
Responsive design
- How to make a page responsiveThe basics of responsive design: the viewport meta tag, fluid widths, flexible images and media queries.
- How to make a responsive card gridA card grid in CSS that changes the number of columns to fit the screen by itself, without media queries.
- How to make a responsive font sizeA font that grows smoothly with the screen width: the clamp function with a minimum, a vw-based value and a maximum.
- How to make a responsive image galleryA gallery of same-size photos that changes the number of columns by itself: grid with auto-fill, aspect-ratio and object-fit.
- How to make a responsive navigationNavigation that adapts to the screen: wrapping items, horizontal scrolling or a vertical menu on a phone.
- How to make a responsive videoA video and an embedded player that shrink to the screen width and keep their proportions: aspect-ratio and width 100%.
- How to show an element only on mobile or only on desktopHiding blocks by screen width with media queries, checking the input type with hover and pointer, and what to do instead of duplicating.
- How to stack columns on mobileColumns that stack on a narrow screen: a media query, and flex-wrap with flex-basis without any media queries.
- How to use container queriesComponent styles based on the width of its container, not the whole screen: container-type and the @container rule.
- How to use media queriesMedia queries in CSS: styles for phones and wide screens with min-width and max-width, breakpoints and ranges.
Text and fonts
- How to add a text shadowText shadows in CSS: the text-shadow property, several shadows, a glow and readable text over an image.
- How to change letter spacingLetter spacing in CSS: letter-spacing for letters, word-spacing for words and when to use them.
- How to change the fontThe font of text in CSS: font-family with fallbacks, a font for the whole page and the system font.
- How to change the font sizeText size in CSS: the font-size property and which units to pick — px, rem or em.
- How to change the line spacingThe space between lines of text: the line-height property, why it is best written without units and how it differs from paragraph margins.
- How to change the text selection colorThe color of text selected with the mouse: the ::selection pseudo-element and which properties work in it.
- How to make gradient textA gradient fill for letters: background-clip text with a transparent text color and a fallback color.
- How to make multi-column textNewspaper columns in CSS: the columns property, gaps and rules between columns, a heading across all columns.
- How to make text bold or italicBold and italic text: the font-weight and font-style properties and when you need the strong and em tags instead.
- How to make text uppercaseUppercase, lowercase and a capital first letter in every word: the text-transform property.
- How to number headings automaticallyAutomatic heading numbers with CSS counters: counter-reset, counter-increment, counter() in ::before and nested numbers like 1.1 and 1.2.
- How to prevent text wrappingText on one line: white-space nowrap, a non-breaking space for single words and text-wrap balance for even headings.
- How to style the first letterA drop cap in CSS: the ::first-letter pseudo-element, the initial-letter property and first-line styles with ::first-line.
- How to truncate text with an ellipsisTruncating long text in CSS: one line with text-overflow and several lines with line-clamp.
- How to underline text and style the underlineUnderlines in CSS: text-decoration, the line's color, thickness and offset, wavy and dotted underlines.
- How to use a custom fontAdding a font to a site: the @font-face rule for your own file, a link to a font service and font-display swap.
- How to use a variable fontA variable font: one file instead of a set of weights, any weight with font-weight, axes with font-variation-settings and smooth animation.
- How to use Google FontsConnecting Google Fonts: the link code for head, the font name in font-family, a system fallback font and hosting the files yourself.
- How to wrap long wordsLong links and words that overflow their box: overflow-wrap anywhere, word-break and automatic hyphens.
Links and buttons
- How to add an icon to a buttonA button with an icon: SVG inside a button, alignment with inline-flex and an icon-only button labeled for screen readers.
- How to change a link's color and remove the underlineStyling links in CSS: the color, text-decoration, the underline offset and the hover state.
- How to change the focus outlineA custom focus outline with :focus-visible and outline: noticeable for the keyboard and invisible on mouse click.
- How to disable a button or a linkA disabled button with the disabled attribute, styling it with :disabled and how to disable a link.
- How to link to a section of the pageAn anchor link in HTML: an id on the section, an href with a hash, smooth scrolling and an offset for a fixed header.
- How to make a file download linkA download link in HTML: the download attribute, a custom file name and a hint about the type and size.
- How to make a link look like a buttonA link that looks like a button: display inline-block, padding, background and the choice between a and button.
- How to make a phone or email linkThe tel: and mailto: links in HTML: a call on tap, an email with a subject and the correct number format.
- How to open a link in a new tabA link in a new tab in HTML: the target and rel attributes, and when it is worth doing.
- How to remove the default button stylesResetting a button: all unset or the background, border, font and padding — so the button looks like text or an icon.
- How to style a buttonStyling a button in CSS: color, padding, rounding and reactions to hover and press.
- How to style link states: visited, hover, focusThe link pseudo-classes :link, :visited, :hover, :focus-visible and :active and the order to write them in.
Colors, backgrounds and borders
- How to add a border to one sideA border on one side in CSS: border-left, border-bottom and the logical border-inline-start, plus an accent bar on a quote.
- How to add a gradient backgroundGradients in CSS: linear with a direction and several colors, radial and hard stripes.
- How to add an outlineThe outline property: an outline that takes no space, outline-offset and a visible focus for keyboard users.
- How to change the background colorBackground color in CSS: background-color, color formats and the background of the whole page.
- How to make a circleA circle in CSS: a square with border-radius 50%, a circle with text or a number inside and aspect-ratio.
- How to make a dark themeA dark theme that follows the system setting: color-scheme, the light-dark() function and the prefers-color-scheme media query.
- How to make a dashed borderDashed and dotted borders in CSS: the border styles dashed, dotted, double and a file drop zone.
- How to make a transparent backgroundA see-through background without see-through text: a color with an alpha channel in rgb, hsl or hex instead of opacity.
- How to make rounded cornersRounded corners in CSS: border-radius for all or single corners, a pill shape and clipping an image inside.
- How to set an accent colorThe accent-color property: your own color for checkboxes, radio buttons, sliders and progress bars in one line.
- How to use CSS variables for colorsA site palette in custom properties: declaring them in :root, var() with a fallback and overriding them for a block.
Images and media
- How to add a caption to an imageAn image caption with figure and figcaption, its styling and a caption over the image.
- How to add a site icon (favicon)A favicon with link rel icon: SVG, PNG and ICO formats, an icon for iPhone and the dark theme.
- How to add a video to a pageThe video element: playback controls, a poster cover, several formats with source and subtitles with track.
- How to add audio to a pageThe audio element: a built-in player, several formats, looping, preloading and the player width.
- How to autoplay a muted videoA background video: the autoplay, muted, loop and playsinline attributes and why autoplay fails without muted.
- How to crop an imageCropping an image in CSS: aspect-ratio with object-fit, choosing the visible part with object-position and clip-path.
- How to darken an image under textDarkening a background for readable text: a gradient over background-image, a pseudo-element and filter brightness.
- How to embed a YouTube video, a map or another siteThe iframe element: embedding another page, the mandatory title, lazy loading and sandbox restrictions.
- How to fit an image into a box without distortionobject-fit cover and contain: the image fills a box of a set size and does not stretch.
- How to lazy-load imagesThe loading lazy attribute: images load only when scrolling reaches them, and why width and height are needed.
- How to make a round imageA round avatar in CSS: border-radius 50% and object-fit for non-square images.
- How to make an iframe responsiveA fluid iframe for videos and maps: width 100% and aspect-ratio instead of the old padding-top trick.
- How to make an image responsiveA fluid image in CSS: max-width 100%, height auto and the width and height attributes against page jumps.
- How to serve sharp images for Retina screensThe srcset attribute: files for high pixel density screens (1x, 2x) and choosing a size by width (w and sizes).
- How to set a background imageA background image in CSS: background-image, the cover size, position, repeat and a fallback color.
- How to show different images on different screensThe picture element: another shot on a phone, a separate image for the dark theme and WebP or AVIF with a JPEG fallback.
- How to use WebP and AVIF images with a fallbackModern image formats: picture with source and the type attribute, the order of formats, srcset for sizes and converting files.
- How to wrap text around an image shapeText that flows around an image along a circle or a polygon: float and shape-outside with circle() and polygon(), and the shape-margin gap.
Forms
- How to add and style a field hint (placeholder)The placeholder attribute, its color with ::placeholder and why a hint does not replace a label.
- How to add suggestions to an input fieldA list of options for a field with datalist: suggestions while typing, with the freedom to enter a custom value.
- How to align form labels and fieldsLabels above and to the left of fields: linking a label to a field, a two-column grid and aligning checkboxes.
- How to change the look of a checkbox and a radio buttonStyling checkboxes and radio buttons: accent-color, size and a fully custom look with appearance none.
- How to group form fieldsThe fieldset and legend elements: a group of related fields, styling the frame and disabling the whole group with disabled.
- How to highlight errors in a formHighlighting wrongly filled fields with :user-invalid and :user-valid and an error message under the field without JavaScript.
- How to make a field requiredThe required attribute: the form is not submitted with an empty field, an asterisk at the label and styling with :required.
- How to make a range sliderThe input type range slider: min, max, step, showing the value with output and the color with accent-color.
- How to make a search fieldSite search: input type search, the search element, a button next to the field and a magnifier icon inside.
- How to make a toggle switchAn on/off switch from a regular checkbox: appearance none, a pseudo-element knob and :checked.
- How to stop a textarea from resizingThe resize property: disabling resizing, resizing in height only and automatic height with field-sizing.
- How to style a file inputStyling input type file: the ::file-selector-button pseudo-element, choosing several files and limiting types with accept.
- How to style a select dropdownStyles for select: border, padding and a custom arrow with appearance none and a background image.
- How to style input fieldsStyles for input and textarea: border, padding, rounding, font, width and a highlight on focus.
- How to turn off or set up field autofillThe autocomplete attribute: off to disable suggestions and precise values email, tel, new-password for correct autofill.
- How to validate an email, a phone or a field formatValidating input without JavaScript: the email and url types, the pattern attribute, minlength, min and max.
Lists and tables
- How to add borders to a tableTable borders in CSS: border-collapse, cell padding and lines between rows only.
- How to align table columnsAlignment in a table: numbers to the right, text-align for a column with nth-child, vertical-align and equal-width digits.
- How to change list markersCustom markers for ul: list-style-type with a string or an emoji, the color with ::marker and an image marker with ::before.
- How to change list numberingAn ordered list ol: letters and Roman numerals with list-style-type, starting from any number and counting down.
- How to keep a table header fixed while scrollingA sticky table header: position sticky on th, a background for the header and scrolling inside a block of limited height.
- How to make a horizontal menu from a listNavigation from ul in a row: nav, flexbox, gap, separators between items and highlighting the current page.
- How to make a nested listA multilevel list: a nested ul or ol inside li, different markers per level and 1.1, 1.2 numbering with counters.
- How to make a striped tableAlternating table row colors with :nth-child(even), a row highlight on hover and stripes only in tbody.
- How to make a table responsive with scrollingA wide table on a phone: a wrapper with overflow-x auto, no wrapping in cells and a hint for the user.
- How to merge table cellsThe colspan and rowspan attributes: a cell spanning several columns or rows and how not to break the table with extra cells.
- How to remove list bulletsA list without bullets in CSS: list-style none, resetting the indent and keeping the list meaning.
- How to set table column widthsColumn widths: table-layout fixed, colgroup and col, the first row width and truncating long text in a cell.
Effects and animation
- How to add a hover effectChanging an element's look on mouse hover: the :hover pseudo-class, smoothness with transition and keyboard focus.
- How to add a shadowBox shadows in CSS: the box-shadow property, soft and layered shadows, an inner shadow and a shadow on hover.
- How to add a smooth transitionSmooth style changes in CSS: the transition property, duration, easing functions and delay.
- How to animate height to autoSmoothly expanding a block to its content height: interpolate-size allow-keywords, the calc-size() function and the grid-template-rows fallback.
- How to animate opening a dialog or popoverSmooth showing and hiding of dialog and popover with CSS: @starting-style for the entry and transition-behavior allow-discrete for display and overlay.
- How to blur the backgroundThe frosted glass effect: backdrop-filter blur with a semi-transparent background, and blurring the element itself with filter.
- How to make a fade-in animationFading an element in: animation with @keyframes, sliding up from below and @starting-style for elements shown later.
- How to make a loading spinnerA spinning loader in pure CSS: a circle with a colored border, @keyframes with rotation and a label for screen readers.
- How to make a pulse animationA pulse in CSS: growing and shrinking with scale, a spreading ring from box-shadow and an endless loop.
- How to make a reading progress barA bar that grows as you scroll: a scroll-driven animation with animation-timeline and scroll(), no JavaScript, and a fallback.
- How to make an image grayscaleA black-and-white photo in CSS with filter grayscale, bringing color back on hover and other filters: brightness, sepia, contrast.
- How to respect reduced motionThe prefers-reduced-motion media query: removing or softening animations when someone turned on reduced motion in their system.
- How to rotate an elementRotation in CSS: the rotate property and the rotate() function in transform, the pivot point and rotating on hover.
- How to scale an element on hoverEnlarging a card or an image on hover: the scale property with transition and zooming an image inside a frame.
Ready-made UI components
- How to make a badgeSmall New labels and notification counters: a span with rounding, a circle with a number in the corner of a button.
- How to make a cardA product or article card: an image, a heading, text and a button at the bottom, rounding and a shadow, the whole card as a link.
- How to make a carousel with scroll-snapA swipeable strip of cards or slides in CSS: horizontal scrolling and scroll-snap so each slide lands neatly.
- How to make a dropdown menuA dropdown menu without JavaScript: details with absolute positioning and the popover attribute for a menu above the whole page.
- How to make a hamburger menu without JavaScriptA menu opened by a three-line button in pure CSS: a checkbox, label and :has(), plus a popover variant.
- How to make a modal dialogA modal window with the dialog tag: opening with showModal, closing with a form, dimming the page with ::backdrop.
- How to make a pricing tableA pricing section: cards on grid, a highlighted recommended plan and buttons on the same level.
- How to make a progress barA progress indicator: the progress tag with styling, a custom bar on a div with the progressbar role and the meter gauge.
- How to make a toast notificationA short notice in the corner of the screen: a block with position fixed, showing it with popover, an animation and auto-hiding with a script.
- How to make a tooltipA hover hint: the title attribute, a custom tooltip with ::after and a data attribute, and showing it on keyboard focus.
- How to make an accordionExpanding sections with details and summary and no JavaScript: styling, a custom icon and only one open section with name.
- How to make breadcrumbsThe navigation trail Home / Section / Page: nav and ol, separators with ::before and aria-current for the current page.
- How to make tabsSwitchable tabs in CSS: radio buttons, label and :checked, and when you need JavaScript and ARIA roles.
- How to position a tooltip next to a button with anchor positioningCSS anchor positioning: anchor-name, position-anchor, position-area and anchor(), a tooltip in a popover and flipping when space runs out.
Page, SEO and accessibility
- How to add a Skip to content linkA skip link for the keyboard: a hidden link at the start of the page that appears on focus and leads to main.
- How to add print stylesThe @media print query: hiding the menu and buttons, black text on white, link addresses and page breaks.
- How to add the viewport meta tag for mobileThe viewport meta tag: why a phone needs it, the right value and why zooming must not be disabled.
- How to check HTML for errorsChecking markup with the W3C validator: how to submit a page, how to read the messages and why the browser silently fixes errors.
- How to connect a CSS file to a pageAn external stylesheet with link rel stylesheet, file paths, the style tag and the order of connection.
- How to hide a page from search enginesThe robots noindex meta tag, nofollow for links, the robots.txt file and how they differ.
- How to make a page accessibleAccessibility basics: alt on images, labels for fields, real buttons, a visible focus, contrast and heading order.
- How to mark up a page with semantic tagsA page skeleton from header, nav, main, article, aside and footer instead of plain divs, and why it matters.
- How to set the page languageThe lang attribute on html and on fragments: screen reader pronunciation, hyphenation, quotes and page translation.
- How to set the page title and descriptionThe title and meta description tags: what shows in the tab and in search results and how many characters to write.
- How to set up a link preview for social networks (Open Graph)The og:title, og:description, og:image and og:url meta tags: how a link to the site looks in messengers and social networks.
- How to speed up page loadingA fast page with HTML and CSS: image dimensions and lazy loading, fetchpriority, srcset and sizes, font preload, defer and content-visibility.
Element visibility and order
- How to hide an elementWays to hide an element: display none, the hidden attribute, visibility hidden and opacity — and how they differ.
- How to hide an element visually but keep it for screen readersThe sr-only (visually-hidden) class: text is not visible on screen but screen readers read it.
- How to make an element non-clickablepointer-events none for clicking through an element, the inert attribute to block a whole area and disabled for fields and buttons.
- How to prevent page scrolling under a modal dialogLocking body scroll with overflow hidden and :has(dialog[open]), overscroll-behavior and the jump caused by the scrollbar.
- How to prevent text selectionThe user-select property: none for buttons and controls, all for selecting with one click and the selection color with ::selection.
- How to show an element on hoverRevealing a block when hovering over its parent: :hover, opacity with transition and :focus-within for the keyboard.
- How to swap elementsThe order of elements without changing HTML: the order property in flexbox and grid, flex-direction reverse and grid-template-areas.