Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Tạo Media Dependent Stylesheets với CSS

Media dependent stylesheets (Stylesheet phụ thuộc media) về cơ bản là các stylesheet bình thường nhưng chỉ áp dụng cho tài liệu HTML khi mediatype khớp với loại thiết bị hiển thị tài liệu.

3 cách tạo Media Dependent Stylesheets

  1. Sử dụng @media At-rules
  2. Sử dụng @import At-rules
  3. Sử dụng phần tử HTML <link> với thuộc tính media

Cách 1: HTML <link> với media attribute

<!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>

screen.css (hiển thị trên màn hình):

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

print.css (khi in ấn):

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

Cách 2: @media trong CSS

<style>
p {
    background-origin: content-box;
    background-repeat: no-repeat;
    background-size: cover;
    box-shadow: 0 0 3px black;
    padding: 20px;
}
@media screen and (max-width: 900px) {
    p {
        background: url("android.jpg");
        color: #c303c3;
    }
}
@media screen and (max-width: 500px) {
    p {
        color: black;
        background: url("react-native.jpg");
    }
}
</style>

Cách 3: @import (Không khuyến khích cho performance)

@import url("screen.css") screen;
@import url("print.css") print;
@import url("mobile.css") screen and (max-width: 600px);

Lưu ý: @import chặn rendering, nên đặt ở đầu file CSS. Hiện nay khuyến nghị dùng <link> thay thế.

Ứng dụng thực tế: Print Stylesheet

@media print {
    .no-print { display: none !important; }
    .only-print { display: block !important; }
    a::after { content: " (" attr(href) ")"; }
    body { font-size: 12pt; line-height: 1.5; color: #000; background: #fff; }
    .page-break { page-break-before: always; }
}

Modern: prefers-color-scheme

@media (prefers-color-scheme: dark) {
    :root { --bg: #1a1a1a; --text: #f0f0f0; }
}
@media (prefers-color-scheme: light) {
    :root { --bg: #ffffff; --text: #1a1a1a; }
}