You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Colab打开时默认折叠所有代码单元格?

How to Default Hide All Code Cells in 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:

  1. Insert a new code cell at the top of your notebook.
  2. 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
});
  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:32:45