# [Style] Safari 中使用 `-webkit-line-clamp`, `display: -webkit-box`, `overflow: hidden` 及 `-webkit-box-orient: vertical` 無法讓多個項目超過指定行數變 ... ###### tags: `前端筆記` `style` ## 問題 今天在公司上遇到 Safari 中容器使用 `-webkit-line-clamp: 3` 其項目無法成功達到超過 3 行出 ... 的效果,先問 ChatGPT 後再 Google 發現 Safari 內 `-webkit-line-clamp` 「並不接受多個項目」,但只要當要隱藏時在容器多設定 CSS 讓項目都是 `display: inline` 後,就可以在 Safari 達到需求。 專案是使用 React 開發,但為求簡單記錄找到的解答,因此改成用基本的三本柱實現。 HTML ```htmlembedded! <div class="container isHidden"> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing</p> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing</p> </div> <button data-expand-btn>展開</button> ``` CSS ```CSS! * { padding: 0; margin: 0; box-sizing: border-box; } .container { width: 700px; border: 1px solid black; } .container.isHidden { /* 超過 3 行出 ... 的 properties combom */ display: -webkit-box; overflow: hidden; -webkit-line-clamp: 3; -webkit-box-orient: vertical; } /* .container 的項目其實是兩個 p elements,在 chrome 中 -webkit-line-clamp 是 可以接受多個項目的,但是在 Safari 中不行,但可以透過 css 改變項目的 display: inline 讓其子項目視為「單行」 */ .container.isHidden > * { display: inline; } .expanded { width: 700px; display: block; } ``` JS ```javascript! // elements const btn = document.querySelector('[data-expand-btn]') const container = document.querySelector('.container') console.log(btn) // state let isHidden = true btn.addEventListener('click', () => { isHidden = !isHidden if (!isHidden) { container.classList.remove('isHidden') container.classList.add('expanded') btn.textContent = '隱藏' } else { container.classList.remove('expanded') container.classList.add('isHidden') btn.textContent = '展開' } }) ``` ## 結果 > 容器都有給 `border` 但截圖的時候沒截好 XD 1. Chrome ![](https://hackmd.io/_uploads/B14bWS-M2.png) ![](https://hackmd.io/_uploads/By4WWrWGn.png) 2. Firefox ![](https://hackmd.io/_uploads/H1SG-HWG3.png) ![](https://hackmd.io/_uploads/SySz-HZM2.png) 3. Safari ![](https://hackmd.io/_uploads/S1KsbBWf2.png) ![](https://hackmd.io/_uploads/r1KsWr-zh.png) ## 完整程式範例 https://codepen.io/lun0223/pen/RwePRyE ## 參考資料 [line clamp (webkit) not working in safari](https://stackoverflow.com/questions/70897195/line-clamp-webkit-not-working-in-safari)