Trong CSS,thuộc tính !important dùng để tăng độ ưu tiên cho một thuộc tính/giá trị. Nó buộc một style ghi đè các khai báo khác, đảm bảo giá trị được áp dụng. Thuộc tính này giúp giải quyết xung đột, nhưng nên dùng hạn chế để tránh làm phức tạp stylesheet.
Cú pháp:
element {
color: blue !important;
font-size: 14px !important;
...
}
Ví dụ 1: Trong ví dụ này, ta dùng CSS đặt màu <h1> thành trắng với !important, ghi đè màu xanh. Phần body có nền vàng, dù có !important xanh do được định nghĩa sau.
HTML<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<style>
h1 {
color: blue;
}
h1 {
color: white !important;
}
body {
background-color: green !important;
text-align: center;
background-color: yellow;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>!important property</h2>
</body>
</html>
Kết quả:
Ví dụ 2: Ví dụ này minh họa thuộc tính !important trong CSS, nó buộc các style như màu sắc, kích thước, nền. Bất chấp các quy tắc xung đột, !important đảm bảo các phần tử .geeks và #gfg tuân theo style chỉ định.
HTML<!DOCTYPE html>
<html>
<head>
<title>!important property</title>
<style>
.geeks {
color: green !important;
size: 10ex !important;
background-color: lightgray !important;
}
.geeks {
color: red;
size: 100ex;
text-align: justify;
background-color: purple;
}
h1,
h2 {
text-align: center;
}
h1 {
color: green;
}
body {
width: 65%;
margin-left: 15%;
}
#gfg {
color: lightgreen !important;
size: 10ex !important;
text-align: justify !important;
background-color: darkgreen !important;
}
#gfg {
color: orange;
size: 1000ex;
background-color: magenta;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>!important property</h2>
<div class=geeks>
A Computer Science portal for geeks.
It contains well written, well thought and well explained
computer science and programming articles and quizzes.
</div>
<div id=gfg>
<p>
Computer programming is the process of writing
instructions that get executed by computers. The
instructions, also known as code, are written in
a programming language which the computer can
understand and use to perform a task or solve a
problem.
</p>
</div>
</body>
</html>
Kết quả:
CSS là nền tảng của trang web, được dùng để phát triển web bằng cách tạo kiểu cho website. Bạn có thể học CSS từ đầu theo CSS Tutorial và CSS Examples.