본문으로 건너뛰기Skip to content
예제 첫화면Examples home

컬럼 폭을 끌어서 바꾸기Drag to resize columns

헤더 경계를 끌면 폭이 바뀌어요. 고정 컬럼도 되고, 최소·최대 폭과 컬럼별 잠금도 정할 수 있어요. 코드로 지정하거나 내용에 맞춰 한 번에 줄이는 것도 쉬워요.Drag a header border to resize. Pinned columns work too, and min/max widths and per-column locks are supported. You can also set widths in code or fit them to the content.

입문Beginner
직접 써 보기Live preview컬럼 폭을 끌어서 바꾸기Drag to resize columns

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="addressWide">주소를 320px로</button>
    <button type="button" id="fitContent">내용에 맞춰 줄이기·늘리기</button>
    <button type="button" id="reset">처음 폭으로</button>
    <select aria-label="폭 조절" id="lock">
      <option value="free" selected>자유롭게</option>
      <option value="locked">잠금</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('addressWide').addEventListener('click', () => actions.addressWide(api));
document.getElementById('fitContent').addEventListener('click', () => actions.fitContent(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
document.getElementById('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
example.js
// 고객 주문 목록. 주소처럼 길쭉한 글이 있어서 폭을 조절할 이유가 보이는 표예요.
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
const addresses = [
  '서울특별시 강남구 테헤란로 152',
  '부산광역시 해운대구 해운대해변로 264',
  '대전광역시 유성구 대학로 99',
  '제주특별자치도 제주시 첨단로 242',
  '경기도 성남시 분당구 판교역로 235',
  '광주광역시 서구 상무중앙로 110',
];
const items = [
  '유기농 사과 10kg',
  '냉동 만두 20봉',
  '사무용 의자',
  '포장 박스 500매',
  '전동 킥보드',
];
export const options = {
  columns: [
    // 고정(pinned) 컬럼도 폭을 바꿀 수 있어요.
    { id: 'customer', title: '고객사', width: 110, pinned: 'start', minWidth: 80 },
    { id: 'address', title: '주소', width: 130, minWidth: 80, maxWidth: 420 },
    { id: 'phone', title: '연락처', width: 120 },
    { id: 'item', title: '주문 상품', width: 120 },
    { id: 'amount', title: '금액(원)', kind: 'number', width: 100, align: 'end', resizable: false },
  ],
  rows: Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    customer: customers[i % 6],
    address: addresses[(i * 5) % 6],
    phone: `0${[2, 51, 42, 64, 31, 62][i % 6]}-555-${String(1000 + i * 137).slice(0, 4)}`,
    item: items[i % 5],
    amount: 48000 + ((i * 91000) % 700000),
  })),
  rowKey: 'id',
  // 'fill'이 기본이라 폭이 남으면 비율대로 나눠 가져요. 사용자가 직접 바꾼 폭은 그대로 지켜요.
  columnFit: 'none',
};
const INITIAL = {
  customer: 110,
  address: 130,
  phone: 120,
  item: 120,
  amount: 100,
};
// 각 컬럼에서 가장 긴 글(헤더 포함)의 실제 폭을 캔버스로 재서 맞춰요.
function fitToContent(api, ids) {
  const probe = document.querySelector('.mxg-cell') ?? document.body;
  const style = getComputedStyle(probe);
  const ctx = document.createElement('canvas').getContext('2d');
  if (!ctx)
    return;
  ctx.font = `${style.fontSize} ${style.fontFamily}`;
  for (const id of ids) {
    const column = api.getColumns().find((c) => c.id === id);
    if (!column || column.resizable === false)
      continue;
    const key = (column.key ?? column.id);
    const texts = [column.title ?? id, ...api.getRows().map((row) => String(row[key]))];
    const widest = Math.max(...texts.map((t) => ctx.measureText(t).width));
    api.resizeColumn(id, Math.ceil(widest) + 32); // 좌우 여백 + 정렬 표시 자리
  }
}
let say = () => { };
export function setup(api, log) {
  say = log;
  const off = api.on('columnResized', ({ columnId, previousWidth, width, source }) => {
    const title = api.getColumns().find((c) => c.id === columnId)?.title ?? columnId;
    const by = { pointer: '마우스', keyboard: '키보드', menu: '메뉴', api: '코드' }[source];
    const byEn = { pointer: 'mouse', keyboard: 'keyboard', menu: 'menu', api: 'code' }[source];
    log({
      ko: `${title}: ${previousWidth}px → ${width}px (${by})`,
      en: `${title}: ${previousWidth}px → ${width}px (${byEn})`,
    });
  });
  return () => off();
}
export const actions = {
  // 코드로 폭을 지정해요(resizeColumn). 최소·최대 폭 안으로 알아서 맞춰져요.
  addressWide: (api) => api.resizeColumn('address', 320),
  // 내용에 맞춰 모든 컬럼을 한 번에 줄이거나 늘려요.
  fitContent: (api) => fitToContent(api, ['customer', 'address', 'phone', 'item']),
  reset: (api) => {
    // 잠근 컬럼(금액)은 코드로도 바꿀 수 없으니 건너뛰어요.
    for (const [id, width] of Object.entries(INITIAL)) {
      if (api.getColumns().find((c) => c.id === id)?.resizable !== false)
        api.resizeColumn(id, width);
    }
  },
  // 'locked'이면 마우스·키보드로 폭을 못 바꿔요(코드의 resizeColumn은 그대로 돼요).
  lock: (api, value) => {
    api.setOptions({ columnsResizable: value !== 'locked' });
    say({
      ko: value === 'locked' ? '폭 조절을 잠갔어요' : '폭 조절을 풀었어요',
      en: value === 'locked' ? 'Column resizing locked' : 'Column resizing unlocked',
    });
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="addressWide">Address to 320px</button>
    <button type="button" id="fitContent">Fit to content</button>
    <button type="button" id="reset">Reset widths</button>
    <select aria-label="Resizing" id="lock">
      <option value="free" selected>Free</option>
      <option value="locked">Locked</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('addressWide').addEventListener('click', () => actions.addressWide(api));
document.getElementById('fitContent').addEventListener('click', () => actions.fitContent(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
document.getElementById('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
example.js
// A customer order list. Long text such as the address gives a reason to adjust column widths.
const customers = [
  'Northwind Logistics',
  'Bluesky Foods',
  'Polaris Trading',
  'Harbor & Co.',
  'Dawn Farms',
  'Mode Fashion',
];
const addresses = [
  '152 Market Street, San Francisco, CA',
  '264 Ocean Parkway, Brooklyn, New York',
  '99 University Avenue, Austin, Texas',
  '242 Innovation Drive, Seattle, Washington',
  '235 Station Road, Princeton, New Jersey',
  '110 Central Boulevard, Denver, Colorado',
];
const items = [
  'Organic apples 10kg',
  'Frozen dumplings 20 packs',
  'Office chair',
  'Packing boxes 500 pcs',
  'Electric scooter',
];
export const options = {
  columns: [
    // Pinned columns can be resized too.
    { id: 'customer', title: 'Customer', width: 140, pinned: 'start', minWidth: 80 },
    { id: 'address', title: 'Address', width: 130, minWidth: 80, maxWidth: 420 },
    { id: 'phone', title: 'Phone', width: 120 },
    { id: 'item', title: 'Ordered item', width: 130 },
    {
      id: 'amount',
      title: 'Amount ($)',
      kind: 'number',
      width: 100,
      align: 'end',
      resizable: false,
    },
  ],
  rows: Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    customer: customers[i % 6],
    address: addresses[(i * 5) % 6],
    phone: `(${[415, 718, 512, 206, 609, 303][i % 6]}) 555-${String(1000 + i * 137).slice(0, 4)}`,
    item: items[i % 5],
    amount: 48 + ((i * 91) % 700),
  })),
  rowKey: 'id',
  // 'fill' is the default, so spare width is shared in proportion. Widths the user changed are kept as they are.
  columnFit: 'none',
};
const INITIAL = {
  customer: 140,
  address: 130,
  phone: 120,
  item: 130,
  amount: 100,
};
// Measure the real width of the longest text in each column (header included) with a canvas and fit to it.
function fitToContent(api, ids) {
  const probe = document.querySelector('.mxg-cell') ?? document.body;
  const style = getComputedStyle(probe);
  const ctx = document.createElement('canvas').getContext('2d');
  if (!ctx)
    return;
  ctx.font = `${style.fontSize} ${style.fontFamily}`;
  for (const id of ids) {
    const column = api.getColumns().find((c) => c.id === id);
    if (!column || column.resizable === false)
      continue;
    const key = (column.key ?? column.id);
    const texts = [column.title ?? id, ...api.getRows().map((row) => String(row[key]))];
    const widest = Math.max(...texts.map((t) => ctx.measureText(t).width));
    api.resizeColumn(id, Math.ceil(widest) + 32); // side padding + room for the sort indicator
  }
}
let say = () => { };
export function setup(api, log) {
  say = log;
  const off = api.on('columnResized', ({ columnId, previousWidth, width, source }) => {
    const title = api.getColumns().find((c) => c.id === columnId)?.title ?? columnId;
    const by = { pointer: 'mouse', keyboard: 'keyboard', menu: 'menu', api: 'code' }[source];
    log(`${title}: ${previousWidth}px → ${width}px (${by})`);
  });
  return () => off();
}
export const actions = {
  // Set a width by code (resizeColumn). It is fitted inside the minimum and maximum width automatically.
  addressWide: (api) => api.resizeColumn('address', 320),
  // Shrink or grow all columns to their content at once.
  fitContent: (api) => fitToContent(api, ['customer', 'address', 'phone', 'item']),
  reset: (api) => {
    // The locked column (amount) cannot be changed even by code, so skip it.
    for (const [id, width] of Object.entries(INITIAL)) {
      if (api.getColumns().find((c) => c.id === id)?.resizable !== false)
        api.resizeColumn(id, width);
    }
  },
  // With 'locked', widths cannot be changed by mouse or keyboard (resizeColumn from code still works).
  lock: (api, value) => {
    api.setOptions({ columnsResizable: value !== 'locked' });
    say(value === 'locked' ? 'Column resizing locked' : 'Column resizing unlocked');
  },
};