ทำซ้ำภาพพื้นหลัง CSS


สารบัญ

    แสดงสารบัญ


CSS พื้นหลังซ้ำ

ตามค่าเริ่มต้น คุณสมบัติ พื้นหลังภาพ จะแสดงภาพซ้ำทั้งแนวนอนและแนวตั้ง

ภาพบางภาพควรแสดงซ้ำเฉพาะแนวนอนหรือแนวตั้ง ไม่เช่นนั้นภาพจะดูแปลกๆ เช่นนี้

ตัวอย่าง

body
{
  background-image: url("gradient_bg.png");
}

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("gradient_bg.png");
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<p>Strange background image...</p>

</body>
</html>


หากรูปภาพด้านบนแสดงซ้ำในแนวนอนเท่านั้น (พื้นหลัง-ซ้ำ: ซ้ำ-x;) พื้นหลังจะมีลักษณะ ดีกว่า:

ตัวอย่าง

body
{
  background-image: url("gradient_bg.png");
  background-repeat: repeat-x;
}

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("gradient_bg.png");
  background-repeat: repeat-x;
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<p>Here, a background image is repeated only horizontally!</p>

</body>
</html>


เคล็ดลับ: หากต้องการแสดงภาพซ้ำในแนวตั้ง ให้ตั้งค่า พื้นหลัง-repeat: Repeat-y;


CSS พื้นหลังซ้ำ: ไม่ซ้ำ

การแสดงภาพพื้นหลังเพียงครั้งเดียวยังระบุโดยคุณสมบัติ พื้นหลังซ้ำ:

ตัวอย่าง

แสดงภาพพื้นหลังเพียงครั้งเดียว:

body
{
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
}

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<p>W3Schools background image example.</p>
<p>The background image only shows once, but it is disturbing the reader!</p>

</body>
</html>


ในตัวอย่างข้างต้น ภาพพื้นหลังจะอยู่ในตำแหน่งเดียวกับข้อความ เราต้องการเปลี่ยนตำแหน่งของภาพเพื่อที่จะได้ไม่ รบกวนข้อความมากเกินไป


ตำแหน่งพื้นหลัง CSS

คุณสมบัติ พื้นหลังตำแหน่ง ถูกนำมาใช้ ระบุตำแหน่งของภาพพื้นหลัง

ตัวอย่าง

วางภาพพื้นหลังไว้ที่มุมขวาบน:

body
{
   
background-image: url("img_tree.png");
   
background-repeat: no-repeat;
   
background-position: right top;
}

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
  margin-right: 200px;
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<p>Here, the background image is only shown once. In addition it is positioned away from the text.</p>
<p>In this example we have also added a margin on the right side, so that the background image will not disturb the text.</p>

</body>
</html>



คุณสมบัติการทำซ้ำพื้นหลังและตำแหน่ง CSS

background-position

กำหนดตำแหน่งเริ่มต้นของภาพพื้นหลัง

background-repeat

ตั้งค่าวิธีการแสดงภาพพื้นหลังซ้ำ