zoukankan      html  css  js  c++  java
  • CSS系列之后代选择器、子选择器和相邻兄弟选择器

    • 后代选择器比子选择器的范围大,包含子选择器,且包含子选择器的“子孙”选择器,后代选择器使用"空格"符号间隔选择器
    • 子选择器:子选择器只是父选择器的一级子元素,使用">"符号链接选择器
    • 相邻兄弟选择器,是拥有相同父元素,且两个元素相邻,使用"+"符号链接

    1. 后代选择器

    • 比如如下html代码,em是h1的后代元素,如下css样式这样写,只会影响h1中的em标签的内容变为红色,不会影响p中em的内容

    css:

    h1 em {color:red;}

     HTML:

    <html>
    <head>
    <style type="text/css">
    h1 em {color:red;}
    </style>
    </head>
    <body>
    <h1>This is a <em>important</em> heading</h1>
    <p>This is a <em>important</em> paragraph.</p>
    </body>
    </html>

    运行结果: 

    • h1 em的写法适用于h1中的的所有em,且不管em嵌套多少层都会适用
    <h1>This is a <span><p><em>important</em></p></span> heading</h1>

     运行结果:

    2. 子选择器

    下面设置h1的子元素strong标签的内容为红色

    第二个h1中,因为strong的父元素不是h1,而是em,所以css中的设置不会对它起作用

    css:

    h1 > strong {color:red;}

    HTML:

    <!DOCTYPE HTML>
    <html>
    <head>
    <style type="text/css">
    h1 > strong {color:red;}
    </style>
    </head>
    
    <body>
    <h1>This is <strong>very</strong> <strong>very</strong> important.</h1>
    <h1>This is <em>really <strong>very</strong></em> important.</h1>
    </body>
    </html>

    运行结果: 

    3. 相邻兄弟选择器

    h1和p拥有相同的父元素body,相邻兄弟选择器需要紧挨着,只会适用于与h1相邻的p标签的内容

    css:

    h1 + p {margin-top:50px;}

    HTML:

    <!DOCTYPE HTML>
    <html>
    <head>
    <style type="text/css">
    h1 + p {margin-top:50px;}
    </style>
    </head>
    
    <body>
    <h1>This is a heading.</h1>
    <p>This is paragraph.</p>
    <p>This is paragraph.</p>
    <p>This is paragraph.</p>
    <p>This is paragraph.</p>
    <p>This is paragraph.</p>
    </body>
    </html>

    运行结果:

    请记住,用一个结合符只能选择两个相邻兄弟中的第二个元素

    所以h1+p只会对第一个p作用,再如下面的例子:

    只会对两个列表的第二个及后面的li起作用,对第一个li不会起作用

    css:

    li + li {font-weight:bold;}

    HTML:

    <!DOCTYPE HTML>
    <html>
    <head>
    <style type="text/css">
    li + li {font-weight:bold;}
    </style>
    </head>
    
    <body>
    <div>
      <ul>
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
      </ul>
      <ol>
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
      </ol>
    </div>
    </body>
    </html>

    运行结果: 

     例程来源:

  • 相关阅读:
    在WinForm应用程序中快速实现多语言的处理
    使用EasyNetQ组件操作RabbitMQ消息队列服务
    在GridControl表格控件中实现多层级主从表数据的展示
    在Winform混合式框架中整合外部API接口的调用
    快看Sample代码,速学Swift语言(3)-运算符
    快看Sample代码,速学Swift语言(1)-语法速览
    基于信封套打以及批量打印的实现过程
    Winform界面中实现通用工具栏按钮的事件处理
    Winform界面中实现菜单列表的动态个性化配置管理
    双指针模板
  • 原文地址:https://www.cnblogs.com/china-fanny/p/11152986.html
Copyright © 2011-2022 走看看