Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

การจัดสไตล์พื้นหลัง Element ด้วย CSS background property

คุณสมบัติ background เป็น shorthand รวมคุณสมบัติพื้นหลังทั้งหมด: background-color, background-image, background-repeat, background-position, background-clip, background-size, background-origin, background-attachment

Syntax

Selector { background: <color> <image> <position> <size> <repeat> <attachment> <origin> <clip>; }

ตัวอย่างที่ 1: พื้นหลัง body พร้อมรูปภาพ

<!DOCTYPE html> <html> <head> <style> body {    background: gray url("https://www.tutorialspoint.com/pytorch/images/pytorch.jpg") no-repeat;    font-size: 1.2em;    color: black; } h2 {    -webkit-text-fill-color: transparent;    -webkit-text-stroke: 1px black; } p {    box-shadow: 0 0 5px 5px black; } </style> </head> <body> <h2><i>PYTORCH Tutorial</i></h2> <p>This is demo text...</p> <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> </ul> </body> </html>

ตัวอย่างที่ 2: พื้นหลังหลายชั้น

<!DOCTYPE html> <html> <head> <style> h2 {    background-color: bisque; } div {    margin: auto;    background-color:orange;    width: 40%; } </style> </head> <body> <h2>Demo Text</h2> <div>demo demo demo demo</div> </body> </html>

คำอธิบายรายละเอียดแต่ละคุณสมบัติ

คุณสมบัติคำอธิบายค่าเริ่มต้น
background-colorสีพื้นหลังtransparent
background-imageรูปภาพ (url(), gradient)none
background-repeatการทำซ้ำ (repeat, no-repeat, repeat-x, repeat-y, space, round)repeat
background-positionตำแหน่งเริ่มต้น (top, center, bottom, left, right, %, px)0% 0% (top left)
background-sizeขนาดรูป (cover, contain, length, %)auto
background-attachmentการเลื่อน (scroll, fixed, local)scroll
background-originจุดอ้างอิง (border-box, padding-box, content-box)padding-box
background-clipพื้นที่ทาสี (border-box, padding-box, content-box, text)border-box

หลายพื้นหลัง (Multiple Backgrounds):

คั่นด้วยคอมม่า เรียงจากบนลงล่าง (ตัวแรกบนสุด):

background: 
  url(img1.png) no-repeat top left,
  url(img2.png) repeat center,
  linear-gradient(red, blue);

Background-clip: text (Text Gradient):

background: linear-gradient(45deg, red, blue);
background-clip: text;
-webkit-background-clip: text;
color: transparent;