|HTML+CSS|Add Style and Animate to Details & Summary

<details>、<summary> 是 HTML5 元素,可以創建可折疊功能,內容只有在切換為「展開」狀態時才可見。
html
Q1:Ask your question
Answer the question
<details>、<summary> 預設是沒有收合動態效果,樣式也很簡單。所以這次範例是用 CSS 來添增樣式和收合動態效果。
首先在 <summary> 內新增 summary-ttl、summary-icon,把摘要文字跟收合 icon 做區隔。
html
Ask your question
Provide an answer
然後清除 <summary> 預設箭頭 icon 、游標改成手指。
css
summary{ cursor: pointer; /* 游標改成手指 */
display: flex; /* 清除預設箭頭 icon */
justify-content: space-between; /* 讓 ttl、icon 貼齊在兩端*/
align-items: center;
}
summary::-webkit-details-marker{
display: none; /* 清除 Safari 預設箭頭 icon */
}
用 ::before、::after 自訂收合 icon。
css
.summary-icon{ display: block;
width: min(4.8vw, 1.5rem);
transform-origin: center 50%;
transition: transform 0.5s;
position: relative;
}
.summary-icon::before,
.summary-icon::after{ content: "";
height: 2px;
display: block;
position: absolute; top: 0;
}
/* style-a 細線箭頭 */
.style-a .summary-icon::before,
.style-a .summary-icon::after{ width: 62%;
background-color: #fff;
}
.style-a .summary-icon::before{ left: 0;
transform: rotate(45deg);
}
.style-a .summary-icon::after{ right: 0;
transform: rotate(-45deg);
}
/* style-b 十字 */
.style-b{ --color-b:#000;}
.style-b .summary-icon{ width: min(4.75vw, 1.4rem); }
.style-b .summary-icon::before,
.style-b .summary-icon::after{ width: 100%; background-color: var(--color-b);
}
.style-b .summary-icon::before{ left: 0%;
transform: rotate(180deg);
}
.style-b .summary-icon::after{ right: 2%;
transform: rotate(90deg);
}
再來設置 details[open] 時的 icon 動態效果。
css
/* style-a 細線箭頭 */
.style-a details[open] .summary-icon{ transform: rotate(180deg);}
/* style-b 十字 */
.style-b details[open] .summary-icon{ transform: rotate(180deg);}
.style-b details[open] .summary-icon::after{ width: 0px;}
最後利用 summary 的 margin-bottom 變化來呈現 details 的收合動態效果。
css
/* details 收合動態效果 */
details summary{ transition: margin 0.8s; }
details:not([open]) summary{ margin-bottom: -0.5rem; }
details[open] summary{ margin-bottom: 0rem;
transition: margin 0.8s;
}