CSS 2 引入了属性选择器。
属性选择器可以根据元素的属性及属性值来选择元素。
如果您希望把包含标题(title)的所有元素变为红色,可以写作:
*[title] {color:red;} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="main.css" /> <script src="main.js"></script> <style> [title] { color: red; } </style> </head> <body> <h1>应用样式:</h1> <h2 title="Hello world">Hello world</h2> <a href="http://">WWWWDC</a> <hr /> <h1>未应用样式:</h1> <h2>Hello world</h2> <a href="http://">WWWWDC</a> </body> </html>与上面类似,可以只对有 href 属性的锚(a 元素)应用样式:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> a[href] { color: red; } </style> </head> <body> <h1>应用样式:</h1> <h2>Hello world</h2> <a href="http://">WWWWDC</a> <hr /> <h1>未应用样式:</h1> <h2>Hello world</h2> <a name="title">WWWWDC</a> </body> </html>还可以根据多个属性进行选择,只需将属性选择器链接在一起即可。
例如,为了将同时有 href 和 title 属性的 HTML 超链接的文本设置为红色,可以这样写
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> a[href][title] { color: red; } </style> </head> <body> <h1>应用样式:</h1> <h2>Hello world</h2> <a title="World Wide Developer Community" href="http://">WWWDC</a> <hr /> <h1>未应用样式:</h1> <h2>Hello world</h2> <a name="title">WWWWDC</a> </body> </html>鼠标悬浮在链接上面时会出现title里的内容