본문 바로가기

CSS/Grid

Grid의 가로폭을 고정하는 방법

간혹 grid의 child에 따라서 grid의 자식들 width가 원하는 대로 나오지 않고 틀어지는 경우가 있다.

아래처럼 글자 속성에 white-space: nowrap;을 넣으면

글자가 줄바꿈되지 않고 한 줄로 길게 늘어지면서 

부모의 grid-template-columns: 1fr 1fr 1fr; 속성을 무시한다.

 

모든 엘리먼트의 width가 동일해야 하지만 글자 때문에 첫 번째 child는 더 이상 줄어들지 않는다.

 

<section class="grid-container">
  <article class="item">가나다라 마바사 아자차카 타파하</article>
  <article class="item"></article>
  <article class="item"></article>
</section>

 

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 10px;
}

.item {
  border: 1px solid grey;
  border-radius: 10px;
  padding: 20px;

  white-space: nowrap; /* 줄바꿈 x */
}

 

이를 해결하려면 .item 옆에 다음 class를 추가한다. (prevent-overflow)

 

<section class="grid-container">
  <article class="item prevent-overflow">가나다라 마바사 아자차카 타파하</article>
  <article class="item"></article>
  <article class="item"></article>
</section>

 

.prevent-overflow {
  overflow-x: auto;
  max-width: 100%;
  width: 100%;
  box-sizing: border-box;
}

 

 

여기에 text-overflow: ellipsis;를 넣으면 글자 끝이 ...으로 바뀐다.

보기 좋아진다.

 

자세한 내용은 아래 링크를 참고하자.

https://webplatform.news/issues/2017-10-03

 

A common page layout consists of one or more fixed-width columns, and one flexible column that takes up the remaining space. In CSS Grid Layout, a flexible column can be specified via the auto or 1fr values, e.g. grid-template-columns: auto 320px. By default, flexible grid columns have a “content-based minimum size.” As a consequence of this, a grid item with overflowing content such as a wide table, can cause its entire column to expand, overflow the grid container, and even push subsequent columns out of the viewport. The following CSS solutions—demonstrated here—can be used to prevent this issue:
  1. Apply overflow-x: auto to a grid item to ensure that its column doesn’t expand undesirably. In the case of content overflow, a horizontal scroll bar appears on the grid item instead (see “Table” scenario).
  2. Apply overflow-x: auto to code blocks. If both the code block and grid item have this value, the scroll bar appears on the code block instead (see “Code block” scenario).
  3. Apply max-width: 100% to images, videos, iframes, etc. to restrict their width to the available space in the grid column (see “Image” scenario).
  4. Apply width: 100% to form controls that are placed in flexible grid cells, to make the controls themselves flexible (see “Dropdown” scenario). This approach works reliably for <input>, <button>, and <select> elements (even when they are wrapped in <div>s). See Dave Rupert’s test case for alternative approaches.