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

การสร้างสไตล์ชีตขึ้นอยู่กับสื่อโดยใช้ CSS


สไตล์ชีตที่ขึ้นกับสื่อเป็นสไตล์ชีตพื้นฐานเท่านั้น แต่ใช้กับเอกสาร html เฉพาะเมื่อประเภทสื่อตรงกับประเภทอุปกรณ์ที่มองเห็นเอกสารได้

เราสามารถสร้างสไตล์ชีตที่ขึ้นกับสื่อได้โดยวิธีการดังต่อไปนี้ -

  • การใช้ @media At-rules
  • การใช้ @import At-rules
  • การใช้ HTML องค์ประกอบที่มีแอตทริบิวต์สื่อ

ตัวอย่าง

มาดูตัวอย่างการสร้างสไตล์ชีตที่ขึ้นกับสื่อกัน −

เอกสาร HTML

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="screen" href="screen.css">
<link rel="stylesheet" type="text/css" media="print" href="print.css">
</head>
<body>
<div></div>
</body>
</html>

เอกสาร CSS (screen.css)

div {
height: 50px;
width: 100px;
border-radius: 20%;
border: 2px solid blueviolet;
box-shadow: 22px 12px 3px 3px lightblue;
position: absolute;
left: 30%;
top: 20px;
}

เอกสาร CSS (print.css)

div {
   height: 50px;
   width: 100px;
   border-radius: 20%;
   border: 2px solid #dc3545;
   box-shadow: 22px 12px 3px 3px #dc3545;
   position: absolute;
   left: 30%;
   top: 20px;
}

ผลลัพธ์

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

เมื่อเอกสารปรากฏอยู่ในประเภทสื่อหน้าจอ −

การสร้างสไตล์ชีตขึ้นอยู่กับสื่อโดยใช้ CSS

เมื่อเอกสารปรากฏอยู่ในสื่อสิ่งพิมพ์ −

การสร้างสไตล์ชีตขึ้นอยู่กับสื่อโดยใช้ CSS

ตัวอย่าง

มาดูตัวอย่างอื่นสำหรับการสร้างสไตล์ชีตที่ขึ้นกับสื่อกัน −

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
p {
   background-origin: content-box;
   background-repeat: no-repeat;
   background-size: cover;
   box-shadow: 0 0 3px black;
   padding: 20px;
   background-origin: border-box;
}
@media screen and (max-width: 900px) {
   p{
      background: url("https://www.tutorialspoint.com/android/images/android.jpg");
      color: #c303c3;
   }
}
@media screen and (max-width: 500px) {
   p {
      color: black;
      background: url("https://www.tutorialspoint.com/react_native/images/react-native.jpg");
   }
}
</style>
</head>
<body>
<p>This is demo text. This is demo text. This is demo text. This is demo text. 
This is demo text. This is demo text. This is demo text. This is demo text. 
This is demo text. This is demo text. This is demo text. This is demo text. 
This is demo text. This is demo text. This is demo text. This is demo text. 
This is demo text. This is demo text. This is demo text. This is demo text. </p>
</body>
</html>

ผลลัพธ์

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

เมื่อขนาดหน้าจอสูงกว่า 500px −

การสร้างสไตล์ชีตขึ้นอยู่กับสื่อโดยใช้ CSS

เมื่อขนาดหน้าจอต่ำกว่า 500px −

การสร้างสไตล์ชีตขึ้นอยู่กับสื่อโดยใช้ CSS