엑셀에 틀 고정이라는 기능이 있다. 틀 고정을 사용하면 상하 또는 좌우로 스크롤해도 항상 보이는 행 또는 열을 만들 수 있다. CSS로도 같은 효과를 낼 수 있다. 이를 구현하기 위해 사용하는 속성은 display: sticky이다.
예를 들어 다음과 같은 표가 있다고 하자.
table#jb-table th, table#jb-table td { padding: 20px 80px; border: 1px solid #444444; }
table#jb-table th { background-color: #eeeeee; }
table#jb-table tbody tr td:first-child { background-color: #eeeeee; }
<th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th><th>G</th>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td>
<th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th><th>G</th>
웹브라우저 창 크기가 충분히 크면 모든 내용을 볼 수 있으나...

그렇지 않은 경우 상하좌우 스크롤이 생긴다.

내용을 보기 위해 스크롤 하다보면 무엇에 대한 값인지 알 수가 없다.

제1행을 고정하고 싶다면 다음 코드를 CSS에 추가한다.
table#jb-table thead { position: sticky; top: 0; }
상하 스크롤을 해도 제1행은 항상 보인다.

제1열을 고정하고 싶다면 다음 코드를 CSS에 추가한다.
table#jb-table th:first-child,
table#jb-table td:first-child { position: sticky; left: 0; }
좌우 스크롤을 해도 제1행은 항상 보인다.

제1행과 제1열을 고정하기 위해, 위에 사용했던 코드를 다 넣으면...
table#jb-table thead { position: sticky; top: 0; }
table#jb-table th:first-child,
table#jb-table td:first-child { position: sticky; left: 0; }
제1행 제1열의 셀이 가려지게 된다.

이를 해결하는 방법은 z-index를 추가하는 것이다.
table#jb-table thead { position: sticky; top: 0; z-index: 1; }
table#jb-table th:first-child,
table#jb-table td:first-child { position: sticky; left: 0; }
이제 상하좌우 스크롤을 해도 제1행과 제1열은 항상 보인다.

마지막 행도 고정하고 싶다면 다음과 같이 한다.
table#jb-table thead { position: sticky; top: 0; z-index: 1; }
table#jb-table th:first-child,
table#jb-table td:first-child { position: sticky; left: 0; }
table#jb-table tfoot { position: sticky; bottom: 0; }
제1열과 제2열을 고정하고 싶다면 다음과 같이 한다. 제2열의 left 값은 제1열의 크기에 맞게 적절히 정한다.
table#jb-table th:first-child,
table#jb-table td:first-child { position: sticky; left: 0; }
table#jb-table th:nth-child(2),
table#jb-table td:nth-child(2) { position: sticky; left: 183px; }
출처 : https://www.codingfactory.net/13033
댓글 없음:
댓글 쓰기