萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

純 CSS 打造日曆圖示:偽元素組合零圖片實現

最終效果

CSS 日曆圖示成品

HTML 結構極簡

<p class="calendar">7<em>February</em></p>

外層 <p> 承載日期數字,內層 <em> 承載月份。HTML5 可改用 <time>。

實現原理:2 個真元素 + 4 個偽元素 = 6 個可樣式化圖層

圖層分解示意
  • 外層 ::before、::after → 兩側圓孔(裝訂孔)。
  • 內層 em::before、em::after → 兩側吊環。
  • 外層本體 → 日曆主卡片(漸層、陰影、圓角)。
  • 內層 em → 月份標籤(漸層、底部圓角、頂部邊框)。

核心 CSS(含廠商前綴)

.calendar {
  margin: .25em 10px 10px 0; padding-top: 5px;
  float: left; width: 80px;
  background: #ededef;
  background: -webkit-gradient(linear, left top, left bottom, from(#ededef), to(#ccc));
  background: -moz-linear-gradient(top, #ededef, #ccc);
  font: bold 30px/60px "Arial Black", Arial, Helvetica, sans-serif;
  text-align: center; color: #000; text-shadow: #fff 0 1px 0;
  -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px;
  position: relative;
  -moz-box-shadow: 0 2px 2px #888;
  -webkit-box-shadow: 0 2px 2px #888;
  box-shadow: 0 2px 2px #888;
}

.calendar em {
  display: block;
  font: normal bold 11px/30px Arial, Helvetica, sans-serif;
  color: #fff; text-shadow: #00365a 0 -1px 0;
  background: #04599a;
  background: -webkit-gradient(linear, left top, left bottom, from(#04599a), to(#00365a));
  background: -moz-linear-gradient(top, #04599a, #00365a);
  -moz-border-radius-bottomright: 3px; -webkit-border-bottom-right-radius: 3px; border-bottom-right-radius: 3px;
  -moz-border-radius-bottomleft: 3px;  -webkit-border-bottom-left-radius: 3px;  border-bottom-left-radius: 3px;
  border-top: 1px solid #00365a;
}

/* 圓孔 */
.calendar::before, .calendar::after {
  content: ''; position: absolute; top: 5px; width: 8px; height: 8px;
  background: #111; z-index: 1;
  -moz-border-radius: 10px; -webkit-border-radius: 10px; border-radius: 10px;
  -moz-box-shadow: 0 1px 1px #fff; -webkit-box-shadow: 0 1px 1px #fff; box-shadow: 0 1px 1px #fff;
}
.calendar::before { left: 11px; }
.calendar::after  { right: 11px; }

/* 吊環 */
.calendar em::before, .calendar em::after {
  content: ''; position: absolute; top: -5px; width: 4px; height: 14px;
  background: #dadada;
  background: -webkit-gradient(linear, left top, left bottom, from(#f1f1f1), to(#aaa));
  background: -moz-linear-gradient(top, #f1f1f1, #aaa);
  z-index: 2;
  -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px;
}
.calendar em::before { left: 13px; }
.calendar em::after  { right: 13px; }

關鍵技術點

  • 無固定 height,高度由 line-height 與 padding 自然撐開,適應字體縮放。
  • 大量使用 CSS3 漸層、圓角、陰影、文字陰影,打造立體質感。
  • 偽元素承擔裝飾角色,HTML 保持純淨語意。

現代優化

  • 移除 -moz-/-webkit- 前綴(現代瀏覽器已標準化)。
  • 使用 linear-gradient() 標準語法替代舊版漸層語法。
  • 可加入 @supports 判斷優雅降級。
copyright © 萬盛學電腦網 all rights reserved