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

컬럼 폭을 비율로 나누기Split column widths by ratio

작업 5 : 담당 2 : 상태 2 : 번호 1처럼 비율로 폭을 나누고 싶을 때는, 가진 폭을 비율대로 계산해서 컬럼마다 폭을 넣어요. 남는 폭을 알아서 나눠 가지게 하는 방법은 '가로 스크롤 없이 폭 맞추기' 예제를 보세요.To lay columns out as a ratio such as 5:2:2:1, work out each width from the space you have and set it per column. To let columns share leftover width automatically, see the fit-width example.

입문Beginner
직접 써 보기Live preview컬럼 폭을 비율로 나누기Split column widths by ratio

코드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">
    <select aria-label="전체 폭" id="width">
      <option value="400">400px (남는 폭은 비움)</option>
      <option value="560">560px (남는 폭은 비움)</option>
      <option value="700">700px (남는 폭은 비움)</option>
      <option value="fit" selected>그리드 폭에 맞춤 (기본)</option>
    </select>
  </div>
  <div id="grid" style="height: 280px"></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);
document.getElementById('width').addEventListener('change', (event) => actions.width(api, event.target.value));
example.js
// 폭은 px로 정해요. 비율(예: 1 : 5 : 2 : 2)로 나누고 싶으면, 가진 폭을 비율대로 px로 바꿔서
// 컬럼마다 resizeColumn을 부르면 돼요.
const RATIOS = { id: 1, title: 5, owner: 2, status: 2 };
function applyRatios(api, total) {
  const sum = Object.values(RATIOS).reduce((a, b) => a + b, 0);
  for (const [id, ratio] of Object.entries(RATIOS)) {
    api.resizeColumn(id, Math.floor((total * ratio) / sum));
  }
}
export const options = {
  columns: [
    { id: 'id', title: '번호 (1)', width: 70, align: 'end', minWidth: 48 },
    { id: 'title', title: '작업 (5)', width: 350, minWidth: 120 },
    { id: 'owner', title: '담당 (2)', width: 140, minWidth: 80 },
    { id: 'status', title: '상태 (2)', width: 140, minWidth: 80 },
  ],
  rows: [
    { id: 101, title: '물류 센터 스캐너 펌웨어 교체', owner: '김민준', status: '진행' },
    { id: 102, title: '분기 공급사 점검 회의', owner: '이서연', status: '완료' },
    { id: 103, title: '반품 정책 안내 페이지 개편', owner: '박지호', status: '진행' },
    { id: 104, title: '신규 입점 상품 가격표 정리', owner: '최유나', status: '예정' },
  ],
  rowKey: 'id',
};
// 처음에도 '그리드 폭에 맞춤'(선택 목록의 기본값)과 같은 모양으로 시작한다.
export function setup(api) {
  requestAnimationFrame(() => actions.width(api, 'fit'));
}
export const actions = {
  // 숫자를 고르면 그 폭 안에서 비율대로 나누고 남는 폭은 비워 둬요.
  // '그리드 폭에 맞춤'은 그리드가 가진 폭을 재서 같은 방법으로 나눠요(window 크기가 바뀌면 다시 골라요).
  width: (api, value) => {
    const fit = value === undefined || value === 'fit';
    const grid = document.querySelector('.mxg');
    applyRatios(api, fit ? Math.max(300, (grid?.clientWidth ?? 700) - 2) : Number(value));
  },
};

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">
    <select aria-label="Total width" id="width">
      <option value="400">400px (leave the rest blank)</option>
      <option value="560">560px (leave the rest blank)</option>
      <option value="700">700px (leave the rest blank)</option>
      <option value="fit" selected>Fit the grid width (default)</option>
    </select>
  </div>
  <div id="grid" style="height: 280px"></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);
document.getElementById('width').addEventListener('change', (event) => actions.width(api, event.target.value));
example.js
// Widths are set in px. To split by a ratio (for example 1 : 5 : 2 : 2), convert the available width
// to px by that ratio and call resizeColumn for each column.
const RATIOS = { id: 1, title: 5, owner: 2, status: 2 };
function applyRatios(api, total) {
  const sum = Object.values(RATIOS).reduce((a, b) => a + b, 0);
  for (const [id, ratio] of Object.entries(RATIOS)) {
    api.resizeColumn(id, Math.floor((total * ratio) / sum));
  }
}
export const options = {
  columns: [
    { id: 'id', title: 'No. (1)', width: 70, align: 'end', minWidth: 48 },
    { id: 'title', title: 'Task (5)', width: 350, minWidth: 120 },
    { id: 'owner', title: 'Owner (2)', width: 140, minWidth: 80 },
    { id: 'status', title: 'Status (2)', width: 140, minWidth: 80 },
  ],
  rows: [
    {
      id: 101,
      title: 'Replace warehouse scanner firmware',
      owner: 'Liam Carter',
      status: 'Active',
    },
    { id: 102, title: 'Quarterly supplier review meeting', owner: 'Emma Stone', status: 'Done' },
    { id: 103, title: 'Revamp returns policy page', owner: 'Noah Parker', status: 'Active' },
    {
      id: 104,
      title: 'Organize price list for new vendor products',
      owner: 'Olivia Reed',
      status: 'Planned',
    },
  ],
  rowKey: 'id',
};
// Start in the same shape as 'Fit to grid width' (the default of the select list).
export function setup(api) {
  requestAnimationFrame(() => actions.width(api, 'fit'));
}
export const actions = {
  // Picking a number splits that width by the ratios and leaves the rest empty.
  // 'Fit to grid width' measures the grid's own width and splits it the same way (pick again after the window is resized).
  width: (api, value) => {
    const fit = value === undefined || value === 'fit';
    const grid = document.querySelector('.mxg');
    applyRatios(api, fit ? Math.max(300, (grid?.clientWidth ?? 700) - 2) : Number(value));
  },
};