後端開發者常需處理前端切版任務。本文針對常見需求——背景圖、文字置中、文字圖片混排、底部背景、區塊置中——提供可直接複製套用的最小化代碼片段,並說明核心原理。
.bg-box {
width: 300px; height: 200px;
background: url("photo.jpg") no-repeat center center;
background-size: cover; /* 覆蓋容器,保持比例 */
/* background-size: contain; 完整顯示圖片,可能留白 */
}
屬性拆解:
background-image:圖片路徑background-repeat:no-repeat、repeat、repeat-x、repeat-ybackground-position:center、top left、50% 50%、10px 20pxbackground-attachment:scroll(預設跟隨捲動)、fixed(固定視窗)background-size:cover、contain、100% 100%、auto.center-text {
display: flex;
align-items: center; /* 垂直 */
justify-content: center; /* 水平 */
height: 200px; /* 必須有高度 */
}
.center-text {
display: grid;
place-items: center;
height: 200px;
}
.center-text {
position: relative;
height: 200px;
}
.center-text span {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
.media {
display: flex; align-items: flex-start; gap: 1rem;
}
.media-img { flex-shrink: 0; width: 80px; height: 80px; object-fit: cover; }
.media-body { min-width: 0; } /* 防止文字撐破彈性容器 */
.article img { float: left; margin: 0 1rem 1rem 0; }
.article::after { content: ""; display: block; clear: both; }
.bottom-bg {
background: url("/images/bg.jpg") no-repeat center bottom;
background-size: cover;
min-height: 300px; /* 確保有空間顯示 */
}
/* 等效拆解寫法 */
.bottom-bg {
background-image: url("/images/bg.jpg");
background-repeat: no-repeat;
background-position: center bottom;
background-size: cover;
}
.box { width: 800px; margin: 0 auto; }
.parent { text-align: center; }
.box { display: inline-block; }
.parent { display: flex; justify-content: center; }
/* 或 */
.parent { display: grid; justify-content: center; }
<div class="card">
<div class="card-img" style="background-image:url('pic.jpg')"></div>
<div class="card-body">
<h3>標題</h3>
<p>描述文字...</p>
</div>
</div>
掌握這幾組核心模式,後端開發者即可獨立完成 80% 以上的切版需求。關鍵在於:背景用 background-size:cover、置中用 Flex/Grid、混排用 Flex gap、底部背景用 background-position:bottom。