Easily Solve the Problem of Oversized YouTube Thumbnails by Customizing Display Columns with a Tampermonkey Script

I. Introduction

In a recent YouTube interface update, the platform increased the size of video thumbnails. While this provides a more direct view of the content on large screens, it has created inconveniences for users who prefer to browse more videos in a single view, leading to a crowded layout and choppy scrolling. This article will guide you on how to use the Tampermonkey extension to write a simple user script to customize the thumbnail layout on the YouTube homepage, making your Browse experience more efficient and comfortable.


II. Prerequisites

1. Install the Tampermonkey Extension Tampermonkey is a popular user script manager that supports major browsers like Chrome, Firefox, and Safari.

2. Understand the Basics of User Scripts A User Script is a piece of JavaScript code that can modify the appearance and functionality of a webpage. With Tampermonkey, we can automatically run these scripts on specific websites to achieve personalized customization.


III. Writing the YouTube Layout Customization Script

1. The Script

JavaScript

// ==UserScript==
// @name         YouTube Grid Columns Customizer (Menu)
// @name:zh-CN   YouTube Thumbnail Column Adjuster
// @namespace    http://tycp.xyz
// @version      1.0
// @description  Allows you to set the number of video columns on the YouTube homepage via a Tampermonkey menu command. Default is 5.
// @description:zh-CN Set the number of video columns displayed per row on the YouTube homepage via the Tampermonkey menu, defaults to 5 columns.
// @author       JYT
// @match        *://www.youtube.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// ==/UserScript==

(function() {
    'use strict';

    const CONFIG_KEY = 'youtubeGridColumnsMenu';
    const DEFAULT_COLUMNS = 5;
    const MIN_COLUMNS = 1;
    const MAX_COLUMNS = 12; // Sensible maximum

    function applyGridColumns(columns) {
        const numColumns = parseInt(columns, 10);
        if (isNaN(numColumns) || numColumns < MIN_COLUMNS || numColumns > MAX_COLUMNS) {
            console.warn(`YouTube Grid Columns: Invalid column number (${columns}). Using default ${DEFAULT_COLUMNS}.`);
            GM_setValue(CONFIG_KEY, DEFAULT_COLUMNS); // Reset to default if invalid value somehow got stored
            columns = DEFAULT_COLUMNS;
        }

        const gridRenderers = document.querySelectorAll('ytd-rich-grid-renderer, ytd-browse[page-subtype="home"] #contents.ytd-rich-grid-renderer');
        if (gridRenderers.length > 0) {
            gridRenderers.forEach(gridRenderer => {
                gridRenderer.style.setProperty('--ytd-rich-grid-items-per-row', columns);
                gridRenderer.style.setProperty('--ytd-rich-grid-item-margin', '8px'); 
            });
            // Force a resize event to make the grid re-flow
            setTimeout(() => window.dispatchEvent(new Event('resize')), 200);
            return true;
        }
        return false;
    }

    function setColumnsViaMenu() {
        const currentColumns = GM_getValue(CONFIG_KEY, DEFAULT_COLUMNS);
        const newColumnsStr = prompt(`Set YouTube homepage video columns (${MIN_COLUMNS}-${MAX_COLUMNS}):`, currentColumns);

        if (newColumnsStr === null) { // User cancelled the prompt
            return;
        }

        const newColumns = parseInt(newColumnsStr, 10);

        if (!isNaN(newColumns) && newColumns >= MIN_COLUMNS && newColumns <= MAX_COLUMNS) {
            GM_setValue(CONFIG_KEY, newColumns);
            applyGridColumns(newColumns);
            alert(`YouTube homepage video columns have been set to: ${newColumns}`);
            console.log(`YouTube Grid Columns: Set to ${newColumns} via menu.`);
        } else {
            alert(`Invalid input. Please enter a number between ${MIN_COLUMNS} and ${MAX_COLUMNS}.`);
        }
    }

    // Register the menu command
    GM_registerMenuCommand('Set YouTube Homepage Columns', setColumnsViaMenu, 'C');

    function init() {
        const initialColumns = GM_getValue(CONFIG_KEY, DEFAULT_COLUMNS);
        
        // Apply on initial load
        setTimeout(() => {
            applyGridColumns(initialColumns);
        }, 500); // Delay to ensure grid is available

        // Use MutationObserver to detect dynamic page changes (e.g., infinite scroll)
        const observer = new MutationObserver((mutationsList, obs) => {
            let foundGrid = false;
            for (const mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    // Check if the target itself is a grid container
                    if (mutation.target.matches && (mutation.target.matches('ytd-browse[page-subtype="home"] #contents') || mutation.target.matches('ytd-rich-grid-renderer'))) {
                         foundGrid = true;
                         break;
                    }
                    // Check if a grid was added in the new nodes
                    if (mutation.addedNodes) {
                        for (const node of mutation.addedNodes) {
                           if (node.nodeType === Node.ELEMENT_NODE) {
                                if (node.matches && (node.matches('ytd-rich-grid-renderer') || node.querySelector('ytd-rich-grid-renderer'))) {
                                    foundGrid = true;
                                    break;
                                }
                           }
                        }
                    }
                }
                if (foundGrid) break;
            }

            if (foundGrid) {
                applyGridColumns(GM_getValue(CONFIG_KEY, DEFAULT_COLUMNS));
            }
        });
        
        // Observe the main page manager for content changes
        const pageManager = document.querySelector('ytd-page-manager');
        if (pageManager) {
             observer.observe(pageManager, { childList: true, subtree: true });
        } else {
            // Fallback to observing the whole document if page-manager isn't found immediately
             observer.observe(document.documentElement, { childList: true, subtree: true });
        }
        
        // Re-apply styles after navigating on YouTube (since it's a single-page application)
         document.addEventListener('yt-navigate-finish', () => {
              setTimeout(() => {
                 applyGridColumns(GM_getValue(CONFIG_KEY, DEFAULT_COLUMNS));
              }, 500); // Delay for safety
         });
    }

    if (document.body) {
        init();
    } else {
        window.addEventListener('DOMContentLoaded', init);
    }
})();

2. Install the Script Click the Tampermonkey icon in the top right of your browser, select “Create a new script…”, paste the script content above into the editor, and save it.

3. Adjust the Settings Navigate to the YouTube homepage. Click the Tampermonkey icon, and you will see the script command “Set YouTube Homepage Columns”. Click on it, enter your desired number of columns, save it, and then refresh the YouTube page. You should immediately see the change in the thumbnail layout.


IV. Frequently Asked Questions (FAQ)

Q1: Why isn’t the script working after installation? A: Please check the following:

  • Ensure the Tampermonkey extension is enabled.
  • Ensure the script itself is enabled (look for a green toggle switch next to the script name in the Tampermonkey dashboard).
  • Make sure you have refreshed the YouTube homepage after installing or enabling the script.

Q2: The script is enabled, but it seems like the JS file isn’t loading? A: This can sometimes be related to browser settings. Go to your browser’s settings -> Extensions -> Manage Extensions and enable “Developer mode”.

Q3: How do I restore the default YouTube layout? A: There are two methods:

  1. Use the script’s menu to set the number of columns back to YouTube’s default (which is usually 4, but you can try 5 as a starting point).
  2. Temporarily disable or uninstall the script from the Tampermonkey dashboard.

Q4: Will this script affect other YouTube functions? A: No. This script is designed only to modify the CSS for the thumbnail grid layout on the homepage and subscription pages. It does not interfere with core functions like search, video playback, or subscriptions.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *