
테이블을 만들다보면 반응형으로 만든다고 해도 모바일에서 보기는 좀 불편하더라….
그래서 반응형 테이블 + 모바일 친화적인 테이블을 만들고자 찾아봤고 방법을 찾았다.
CSS로만 구현을 하면 제대로 동작하지 않는 경우가 있다고 해서 jquery를 추가한 구현 방법을 찾았다.
반응형 테이블
반응형 테이블을 만드는 방법
반응형 테이블을 어떻게 만들 수 있을지 방법을 알아보자.
HTML
<table class="responsive-table">
<thead>
<tr>
<th>과일명</th>
<th>색상</th>
<th>맛</th>
</tr>
</thead>
<tr>
<td>사과</td>
<td>빨갛다(초록색도 있다.)</td>
<td>새콤달콤 + 아삭아삭하다.</td>
</tr>
<tr>
<td>오렌지</td>
<td>주황색</td>
<td>새콤달콤하다.</td>
</tr>
<tr>
<td>배</td>
<td>노란색</td>
<td>달콤하다.</td>
</tr>
</table>
사용된 코드 설명
<table class=”responsive-table”>
:
테이블을 만들고 클래스를 responsive-table로 지정한다.
<th>과일명</th><th>색상</th><th>맛</th>
:
th는 모바일로 보면 가려지고 값만 라벨로 들어간다.
CSS
.responsive-table {
text-align: left;
width: 100%;
}
.responsive-table tbody tr:hover {
background-color: #AAA;
}
@media screen and (min-width: 768px) {
.responsive-table td, .responsive-table th {
padding: 0.4em 0.6em !important;
vertical-align: top;
}
.responsive-table th {
font-weight: bold;
border-bottom: 1px solid var(--global--color-border) !important;
}
}
@media screen and (max-width: 767px) {
.responsive-table thead {
display: none;
}
.responsive-table tr {
display: block;
position: relative;
padding: 1.2rem 0 !important;
}
.responsive-table tr:first-of-type {
border-top: 1px solid var(--global--color-border) !important;
}
.responsive-table td {
display: table-row;
}
.responsive-table td:before {
content: attr(data-label);
display: table-cell;
font-weight: bold;
padding: 0.2em 0.6em 0.2em 0 !important;
text-align: right;
}
.responsive-table td:last-child:after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
border-bottom: 1px solid #555 !important;
}
}
사용된 코드 설명
@media screen and (max-width: 767px) { … }
:
화면 크기가 가로로 767px 미만인 기기를 지정하는 코드 = 모바일 & 화면 작은 태블릿
.responsive-table thead { display: none; }
:
모바일에서는 thead가 보이지 않게 한다.
.responsive-table td:before { … }
:
테이블 맨 왼쪽에 들어갈 라벨을 지정하는 코드
content: attr(data-label);
:
data-label로 지정한 th 값들을 content로 사용한다.
.responsive-table td:last-child:after { … }
:
마지막 td 데이터를 다 보여줬다면 td 다음에 보여줄 거 지정하는 코드
border-bottom: 1px solid #555;
:
아래쪽 테두리를 1px의 두께로 만드는 코드
JavaScript
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.responsive-table').forEach(function(table) {
const allThs = Array.from(table.querySelectorAll('th'));
table.querySelectorAll('td').forEach(function(td) {
const tdIndex = td.cellIndex;
const correspondingTh = allThs[tdIndex];
let labelText = '';
if (correspondingTh) {
labelText = correspondingTh.getAttribute('data-label') || correspondingTh.textContent.trim();
}
td.setAttribute('data-label', labelText + ':');
});
});
});
사용된 코드 설명
document.addEventListener( … )
:
특정 이벤트가 발생했을 때 실행할 함수를 등록하는 역할
‘DOMContentLoaded’, function() { … }
:
HTML 문서가 완전히 로드되고 파싱된 후 실행 (이미지/CSS 대기 ❌)
document.querySelectorAll(‘.responsive-table’)
:
.responsive-table인 항목을 선택
forEach(function(table) { … }
:
반복문으로 각 테이블 처리
const tdIndex = td.cellIndex;
:
cellIndex 속성: 현재 td가 속한 행(tr) 내에서의 인덱스
const correspondingTh = allThs[tdIndex];
:
같은 인덱스의 th 찾기
let labelText = ”;
:
변수를 선언하고 빈 문자열로 초기화
if (correspondingTh) { … }
:
현재 td와 같은 열(column)에 위치한 th 요소가 존재하는지 확인하는 조건문
correspondingTh.getAttribute(‘data-label’) || correspondingTh.textContent.trim();
:
th data-label 속성 값 우선 사용하고 속성이 없다면 th의 텍스트 내용 사용
trim()으로 공백 제거 (예: ” Price ” → “Price”)
trim()으로 공백 제거 (예: ” Price ” → “Price”)
td.setAttribute(‘data-label’, labelText + ‘:’);
:
data-label 속성 설정. CSS에서 ::before 가상 요소와 결합해 모바일에서 레이블 표시
보기
EDITOR
VIEWER
참고
Codepen.io - Mobile-Friendly Table
// j.eremy.net - Responsive Table