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

ทำ Responsive Background Image ด้วย CSS

ใช้ background-size: contain หรือ cover ร่วมกับ width: 100% เพื่อทำให้ Background Image Responsive

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        div {
            width: 100%;
            height: 300px;
            border: 2px dashed blue;
            background-image: url('https://www.tutorialspoint.com/python/images/python-data-science.jpg');
            background-repeat: no-repeat;
            background-size: contain; /* หรือ cover */
        }
    </style>
</head>
<body>
    <p>To check the effect, you need to resize the browser.</p>
    <div></div>
</body>
</html>

ความต่าง:

  • contain — แสดงภาพทั้งหมด อาจมีพื้นที่ว่าง
  • cover — ครอบคลุมพื้นที่ทั้งหมด อาจตัดขอบภาพ