如何让Colab打开时默认折叠所有代码单元格?
Yes, it’s possible to make a Colab notebook open with all code cells hidden by default. Your previous approach didn’t work because Colab doesn’t store the folded state of cells in the .ipynb file—this is a UI-specific setting that resets when the notebook is reloaded. Here are two reliable methods:
Method 1: Use #@title Tags for Per-Cell Collapse
Add a #@title comment at the top of each code cell you want hidden by default. You can optionally add a section name after the tag. When you save the notebook, these cells will load in a collapsed state.
Example:
#@title Data Processing Code (Hidden by Default) import pandas as pd df = pd.read_csv('data.csv') # Rest of your code...
This method uses Colab’s native functionality, so it’s stable and less likely to break with UI updates.
Method 2: Auto-Collapse All Cells with JavaScript
If you want to collapse every code cell automatically on load, add a JavaScript code cell to your notebook that triggers the collapse action:
- Insert a new code cell at the top of your notebook.
- Paste this code:
%%javascript window.addEventListener('load', () => { setTimeout(() => { // Target all code cell collapse buttons document.querySelectorAll('.cell.code_cell .collapser').forEach(btn => { const cell = btn.closest('.cell'); if (!cell.classList.contains('collapsed')) { btn.click(); } }); }, 1500); // Delay ensures the UI is fully loaded before running });
- Run this cell once, then save your notebook. Next time you open it, all code cells will collapse automatically.
Note: This relies on Colab’s current UI structure. If Colab changes its HTML classes in the future, you may need to adjust the selector.
内容的提问来源于stack exchange,提问作者starmandeluxe

