前端每日實戰:15# 視頻演示如何用純 CSS 創做條形圖,不用任何圖表庫

圖片描述

效果預覽

按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。javascript

https://codepen.io/zhang-ou/pen/XqzGLpcss

可交互視頻教程

此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。html

請用 chrome, safari, edge 打開觀看。java

https://scrimba.com/c/cJdEgc9git

源代碼下載

請從 github 下載。github

https://github.com/comehope/front-end-daily-challenges/tree/master/015-development-skills-cardspring

代碼解讀

定義 dom,最外層的容器是卡片,內含一個標題,和一個技能說明,分別描述技能的名稱和級別:chrome

<div class="card">
    <h2>Development Skills</h2>
    <p class="skill html">
        <span>HTML5</span>
        <span class="level">90%</span>
    </p>
</div>

居中顯示:canvas

html, body {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(dimgray, silver, silver, dimgray);
}

技能卡片佈局:dom

.card {
    width: 400px;
    background: linear-gradient(#333, dimgray);
    box-sizing: border-box;
    padding: 20px;
    font-family: sans-serif;
    color: white;
    letter-spacing: 0.1em;
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
}

文字佈局:

.card h2 {
    text-transform: uppercase;
    text-align: center;
}

.card .skill {
    height: 50px;
}

.card .skill span {
    display: block;
}

.card .skill .level {
    transform: translateY(-1em);
    text-align: right;
}

用僞元素畫出條形圖:

.card .skill .level {
    position: relative;
}

.card .skill .level::before,
.card .skill .level::after {
    content: '';
    position: absolute;
    top: 1.2em;
    left: 0;
    width: 100%;
    height: 100%;
}

.card .skill .level::before {
    border: 1px solid mediumspringgreen;
    border-radius: 0.2em;
    height: 105%;
}

.card .skill .level::after {
    background-image: linear-gradient(to right, mediumspringgreen, mediumspringgreen);
    background-repeat: no-repeat;
    background-position: top 0.1em left 0.1em;
}

設置條形圖的填充比例:

.card .skill.html .level::after {
    background-size: 90% 1em;
}

dom 增長多個技能,每一個技能用命名不一樣的樣式類:

<div class="card">
    <h2>Development Skills</h2>
    <p class="skill html">
        <span>HTML</span>
        <span class="level">90%</span>
    </p>
    <p class="skill css">
        <span>CSS</span>
        <span class="level">95%</span>
    </p>
    <p class="skill javascript">
        <span>JavaScript</span>
        <span class="level">80%</span>
    </p>
    <p class="skill svg">
        <span>SVG</span>
        <span class="level">60%</span>
    </p>
    <p class="skill canvas">
        <span>Canvas</span>
        <span class="level">75%</span>
    </p>
</div>

分別定義每一個技能的條形圖寬度:

.card .skill.css .level::after {
    background-size: 95% 1em;
}

.card .skill.javascript .level::after {
    background-size: 80% 1em;
}

.card .skill.svg .level::after {
    background-size: 60% 1em;
}

.card .skill.canvas .level::after {
    background-size: 75% 1em;
}

最後,增長一點交互效果:

.card .skill:hover {
    background-color: #333;
}

大功告成!

知識點

相關文章
相關標籤/搜索