Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

Beginner 270 snippets

Bootstrap · Bootstrap 5 hero sectionBeginner
<section class="py-5 text-center bg-light">
  <div class="container py-4">
    <h1 class="display-5 fw-bold">Build something great</h1>
    <p class="lead col-lg-7 mx-auto">One short sentence that explains what you offer and who it is for.</p>
    <div class="d-grid gap-2 d-sm-flex justify-content-sm-center mt-4">
      <a href="#start" class="btn btn-primary btn-lg px-4">Get started</a>
      <a href="#more" class="btn btn-outline-secondary btn-lg px-4">Learn more</a>
    </div>
  </div>
</section>

A simple, centred hero with a heading, short text and two buttons that stack on phones.

CSS · Sticky headerBeginner
header {
  position: sticky;
  top: 0;
  z-index: 50;
  background: #fff;
  box-shadow: 0 1px 0 rgba(0, 0, 0, .08);
}

/* Anchors land below the header */
[id] { scroll-margin-top: 80px; }
html { scroll-behavior: smooth; }
@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }

The header stays at the top while scrolling. Anchor links need scroll-margin so headings do not hide under it.

CSS · Centre anything with FlexboxBeginner
.center {
  display: flex;
  justify-content: center;   /* horizontal */
  align-items: center;       /* vertical */
  min-height: 100vh;
}

/* Even shorter, with Grid */
.center-grid { display: grid; place-items: center; min-height: 100vh; }

The shortest way to centre content both ways.

jQuery · Simple tabsBeginner
// <button class="tab" data-tab="a">One</button> <button class="tab" data-tab="b">Two</button>
// <div class="panel" id="a">…</div> <div class="panel" id="b" hidden>…</div>
$('.tab').on('click', function () {
  const id = $(this).data('tab');
  $('.tab').removeClass('active').attr('aria-selected', 'false');
  $(this).addClass('active').attr('aria-selected', 'true');
  $('.panel').prop('hidden', true);
  $('#' + id).prop('hidden', false);
});

Show one panel at a time. Buttons use data-tab to name their panel.

JavaScript · Validate a form before sendingBeginner
const form = document.querySelector('#signup');

form.addEventListener('submit', (e) => {
  if (!form.checkValidity()) {
    e.preventDefault();
    form.reportValidity();          // shows the browser's own messages
    return;
  }
  // extra rule
  const pw = form.elements.password.value;
  if (pw.length < 12) {
    e.preventDefault();
    form.elements.password.setCustomValidity('Use at least 12 characters.');
    form.reportValidity();
    form.elements.password.setCustomValidity('');   // reset so it can be corrected
  }
});

Use the browser’s built-in Constraint Validation API. Repeat the checks on the server; this only improves the experience.

JavaScript · Use localStorage safelyBeginner
const store = {
  get(key, fallback = null) {
    try { const v = localStorage.getItem(key); return v === null ? fallback : JSON.parse(v); }
    catch (e) { return fallback; }
  },
  set(key, value) {
    try { localStorage.setItem(key, JSON.stringify(value)); return true; }
    catch (e) { return false; }
  }
};

store.set('theme', 'dark');
console.log(store.get('theme', 'light'));

Storage can be blocked or full, and stored text can be broken. Wrap every call in try/catch and keep passwords or tokens out of it.

SQL · JOIN two tablesBeginner
-- Orders with the customer name
SELECT o.id, o.total, c.name
FROM orders AS o
INNER JOIN customers AS c ON c.id = o.customer_id;

-- All customers, including those who never ordered
SELECT c.name, COUNT(o.id) AS orders
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.name;

INNER JOIN returns only matching rows. LEFT JOIN keeps every row from the first table, even without a match.

function group_by(array $rows, string $key): array
{
    $out = [];
    foreach ($rows as $row) {
        $out[$row[$key]][] = $row;
    }
    return $out;
}

$products = [
    ['name' => 'Pen',    'cat' => 'Office'],
    ['name' => 'Laptop', 'cat' => 'Tech'],
    ['name' => 'Paper',  'cat' => 'Office'],
];
print_r(group_by($products, 'cat'));   // Office => [Pen, Paper], Tech => [Laptop]

Turn a flat list of database rows into groups (for example products by category).

PHP · Flash messages (show once)Beginner
function flash(?string $msg = null): ?string
{
    if ($msg !== null) { $_SESSION['flash'] = $msg; return null; }
    $m = $_SESSION['flash'] ?? null;
    unset($_SESSION['flash']);
    return $m;
}

// After saving:
flash('Saved successfully.');
header('Location: /list.php');
exit;

// On the next page:
if ($m = flash()) echo '<p class="notice">' . htmlspecialchars($m, ENT_QUOTES, 'UTF-8') . '</p>';

Store a message in the session before a redirect and show it once on the next page.

PHP · Redirect safely after a formBeginner
function redirect(string $to): never
{
    header('Location: ' . $to, true, 303);   // 303 = "see other": the browser switches to GET
    exit;
}

// Only allow redirects to pages on your own site
function safe_next(string $next, string $fallback = '/'): string
{
    return (preg_match('#^/(?!/)[A-Za-z0-9/_\-.?=&]*$#', $next)) ? $next : $fallback;
}

redirect(safe_next($_GET['next'] ?? '/'));

Always call exit after a redirect, and never redirect to an address taken straight from the URL (open redirect).

$name  = trim((string)($_POST['name'] ?? ''));
$email = trim((string)($_POST['email'] ?? ''));
$age   = filter_var($_POST['age'] ?? '', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 120]]);

$errors = [];
if ($name === '' || mb_strlen($name) > 80)           $errors[] = 'Enter a name up to 80 characters.';
if (!filter_var($email, FILTER_VALIDATE_EMAIL))      $errors[] = 'Enter a valid email address.';
if ($age === false)                                  $errors[] = 'Age must be a number from 1 to 120.';

if (!$errors) {
    // safe to use $name, $email, $age (still use prepared statements for the database)
}

Trim, check and normalise values from a form before using them. Validation rules belong on the server; the browser checks are only a convenience.

Bootstrap · Show and hide with collapseBeginner
<button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#more" aria-expanded="false" aria-controls="more">Show more</button>
<div class="collapse mt-2" id="more">
  <div class="card card-body">Hidden content that appears when you click.</div>
</div>

A button that opens a hidden block.

Bootstrap · A simple hero sectionBeginner
<div class="p-5 mb-4 bg-body-tertiary rounded-3">
  <div class="container-fluid py-5">
    <h1 class="display-5 fw-bold">Custom jumbotron</h1>
    <p class="col-md-8 fs-4">Using utility classes for typography and spacing.</p>
    <a class="btn btn-primary btn-lg" href="#">Learn more</a>
  </div>
</div>

The old jumbotron, made with utilities.

Bootstrap · Tabs and pillsBeginner
<ul class="nav nav-tabs" id="tabs" role="tablist">
  <li class="nav-item" role="presentation"><button class="nav-link active" id="t1" data-bs-toggle="tab" data-bs-target="#p1" type="button" role="tab" aria-controls="p1" aria-selected="true">Home</button></li>
  <li class="nav-item" role="presentation"><button class="nav-link" id="t2" data-bs-toggle="tab" data-bs-target="#p2" type="button" role="tab" aria-controls="p2" aria-selected="false">Profile</button></li>
</ul>
<div class="tab-content p-3">
  <div class="tab-pane fade show active" id="p1" role="tabpanel" aria-labelledby="t1" tabindex="0">Home content</div>
  <div class="tab-pane fade" id="p2" role="tabpanel" aria-labelledby="t2" tabindex="0">Profile content</div>
</div>

Switch panels without writing JavaScript.

Bootstrap · CarouselBeginner
<div id="hero" class="carousel slide" data-bs-ride="carousel">
  <div class="carousel-indicators">
    <button type="button" data-bs-target="#hero" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
    <button type="button" data-bs-target="#hero" data-bs-slide-to="1" aria-label="Slide 2"></button>
  </div>
  <div class="carousel-inner">
    <div class="carousel-item active"><img src="1.jpg" class="d-block w-100" alt="First slide"></div>
    <div class="carousel-item"><img src="2.jpg" class="d-block w-100" alt="Second slide"></div>
  </div>
  <button class="carousel-control-prev" type="button" data-bs-target="#hero" data-bs-slide="prev"><span class="carousel-control-prev-icon" aria-hidden="true"></span><span class="visually-hidden">Previous</span></button>
  <button class="carousel-control-next" type="button" data-bs-target="#hero" data-bs-slide="next"><span class="carousel-control-next-icon" aria-hidden="true"></span><span class="visually-hidden">Next</span></button>
</div>

Slides with controls.

Bootstrap · Tooltips and popoversBeginner
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-title="Tooltip text">Hover me</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="popover" data-bs-title="Title" data-bs-content="Popover body">Click me</button>

<script>
  document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(function (el) { new bootstrap.Tooltip(el); });
  document.querySelectorAll('[data-bs-toggle="popover"]').forEach(function (el) { new bootstrap.Popover(el); });
</script>

These must be initialized with JavaScript.

Bootstrap · DropdownBeginner
<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Actions</button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">Edit</a></li>
    <li><a class="dropdown-item" href="#">Duplicate</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item text-danger" href="#">Delete</a></li>
  </ul>
</div>

A button with a menu.

Bootstrap · A modalBeginner
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#demo">Open modal</button>

<div class="modal fade" id="demo" tabindex="-1" aria-labelledby="demoLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="demoLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">Modal body text.</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save</button>
      </div>
    </div>
  </div>
</div>

Open with a button, close with the X or Escape.

Bootstrap · AccordionBeginner
<div class="accordion" id="faq">
  <div class="accordion-item">
    <h2 class="accordion-header">
      <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#a1" aria-expanded="true" aria-controls="a1">What is Bootstrap?</button>
    </h2>
    <div id="a1" class="accordion-collapse collapse show" data-bs-parent="#faq">
      <div class="accordion-body">A CSS framework.</div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#a2" aria-expanded="false" aria-controls="a2">Is it free?</button>
    </h2>
    <div id="a2" class="accordion-collapse collapse" data-bs-parent="#faq">
      <div class="accordion-body">Yes, MIT licensed.</div>
    </div>
  </div>
</div>

Only one section open at a time.

Bootstrap · Spinners and progressBeginner
<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>
<button class="btn btn-primary" type="button" disabled>
  <span class="spinner-border spinner-border-sm" aria-hidden="true"></span>
  <span role="status">Loading...</span>
</button>

<div class="progress mt-3" role="progressbar" aria-label="Upload" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100">
  <div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 60%">60%</div>
</div>

Loading indicators.

Bootstrap · Responsive images and thumbnailsBeginner
<img src="photo.jpg" class="img-fluid rounded" alt="Responsive photo">
<img src="photo.jpg" class="img-thumbnail" alt="Thumbnail" width="200" height="150">
<figure class="figure">
  <img src="photo.jpg" class="figure-img img-fluid rounded" alt="A mountain">
  <figcaption class="figure-caption">A caption for the image.</figcaption>
</figure>

Images that never overflow.

Bootstrap · Borders, shadows and cornersBeginner
<div class="p-3 border rounded">Border + rounded</div>
<div class="p-3 border border-primary border-2 rounded-3 mt-2">Thick primary border</div>
<div class="p-3 shadow-sm mt-2">Small shadow</div>
<div class="p-3 shadow mt-2 rounded-pill text-center">Shadow + pill</div>
<img src="a.jpg" class="rounded-circle" alt="Avatar" width="64" height="64">

Quick decoration with classes.

Bootstrap · Flex utilitiesBeginner
<div class="d-flex justify-content-between align-items-center gap-3 p-3 border">
  <strong>Title</strong>
  <div class="d-flex gap-2">
    <button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
    <button type="button" class="btn btn-sm btn-danger">Delete</button>
  </div>
</div>
<div class="d-flex flex-column flex-md-row gap-2 mt-3">
  <div class="p-2 border flex-fill">One</div>
  <div class="p-2 border flex-fill">Two</div>
</div>

Layout without writing CSS.

Bootstrap · Show and hide by screen sizeBeginner
<div class="d-none d-md-block">Visible from md and up</div>
<div class="d-block d-md-none">Visible only below md</div>
<div class="d-flex justify-content-between">
  <span>Left</span><span>Right</span>
</div>

Hide on phones, show on desktop (and the reverse).

Bootstrap · Breadcrumb and paginationBeginner
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="#">Home</a></li>
    <li class="breadcrumb-item"><a href="#">Library</a></li>
    <li class="breadcrumb-item active" aria-current="page">Data</li>
  </ol>
</nav>

<nav aria-label="Page navigation">
  <ul class="pagination justify-content-center">
    <li class="page-item disabled"><a class="page-link" href="#" tabindex="-1">Previous</a></li>
    <li class="page-item active"><a class="page-link" href="#">1</a></li>
    <li class="page-item"><a class="page-link" href="#">2</a></li>
    <li class="page-item"><a class="page-link" href="#">Next</a></li>
  </ul>
</nav>

Where you are and how to move.

Bootstrap · List groupBeginner
<ul class="list-group">
  <li class="list-group-item active" aria-current="true">Current</li>
  <li class="list-group-item d-flex justify-content-between align-items-center">
    Inbox <span class="badge text-bg-primary rounded-pill">14</span>
  </li>
  <li class="list-group-item">Archive</li>
</ul>

<div class="list-group mt-3">
  <a href="#" class="list-group-item list-group-item-action">Clickable item</a>
  <a href="#" class="list-group-item list-group-item-action">Another link</a>
</div>

Lists of items or links.

Bootstrap · TablesBeginner
<div class="table-responsive">
  <table class="table table-striped table-hover align-middle">
    <thead class="table-dark">
      <tr><th scope="col">#</th><th scope="col">Name</th><th scope="col">City</th></tr>
    </thead>
    <tbody>
      <tr><th scope="row">1</th><td>Ali</td><td>Lahore</td></tr>
      <tr><th scope="row">2</th><td>Sara</td><td>Karachi</td></tr>
    </tbody>
  </table>
</div>

Styled tables that scroll on small screens.

Bootstrap · Switches and rangeBeginner
<div class="form-check form-switch">
  <input class="form-check-input" type="checkbox" role="switch" id="sw" checked>
  <label class="form-check-label" for="sw">Email notifications</label>
</div>

<label for="vol" class="form-label mt-3">Volume</label>
<input type="range" class="form-range" id="vol" min="0" max="10">

Toggle and slider controls.

Bootstrap · Floating labelsBeginner
<div class="form-floating mb-3">
  <input type="email" class="form-control" id="fe" placeholder="name@example.com">
  <label for="fe">Email address</label>
</div>
<div class="form-floating">
  <input type="password" class="form-control" id="fp" placeholder="Password">
  <label for="fp">Password</label>
</div>

The label sits inside the field.

Bootstrap · Input groupsBeginner
<div class="input-group mb-3">
  <span class="input-group-text">@</span>
  <input type="text" class="form-control" placeholder="Username" aria-label="Username">
</div>
<div class="input-group">
  <input type="search" class="form-control" placeholder="Search" aria-label="Search">
  <button class="btn btn-outline-secondary" type="button">Go</button>
</div>

Text or buttons attached to a field.