萬盛學電腦網

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

Web 後端開發者的 DIV+CSS 實戰速查:佈局、背景、置中、文字圖片混排

前言

後端開發者常需處理前端切版任務。本文針對常見需求——背景圖、文字置中、文字圖片混排、底部背景、區塊置中——提供可直接複製套用的最小化代碼片段,並說明核心原理。

一、div 設定背景圖片

.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-y
  • background-position:center、top left、50% 50%、10px 20px
  • background-attachment:scroll(預設跟隨捲動)、fixed(固定視窗)
  • background-size:cover、contain、100% 100%、auto

二、控制 DIV 中文字絕對置中(水平+垂直)

Flex 方案(推薦,現代瀏覽器全支援)

.center-text {
  display: flex;
  align-items: center;   /* 垂直 */
  justify-content: center; /* 水平 */
  height: 200px; /* 必須有高度 */
}

Grid 方案(最簡潔)

.center-text {
  display: grid;
  place-items: center;
  height: 200px;
}

傳統方案:絕對定位 + transform(IE10+)

.center-text {
  position: relative;
  height: 200px;
}
.center-text span {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

三、CSS 文字加圖片混排佈局

圖文並排(圖左文右)

.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; } /* 防止文字撐破彈性容器 */

文字環繞圖片(傳統 float)

.article img { float: left; margin: 0 1rem 1rem 0; }
.article::after { content: ""; display: block; clear: both; }

四、在 DIV 底部顯示背景圖片

.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;
}

五、div 水平置中顯示

定寬區塊

.box { width: 800px; margin: 0 auto; }

不定寬區塊(行內區塊)

.parent { text-align: center; }
.box { display: inline-block; }

Flex/Grid 父容器置中子元素

.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。

copyright © 萬盛學電腦網 all rights reserved