【问题标题】:selecting an element within other div在其他 div 中选择一个元素
【发布时间】:2017-09-19 11:07:20
【问题描述】:

让我们先看看下面的代码

<div class="div1">
   <p>Hello There</p>
</div>
<div class="div-main">
   <p>Hello There</p>
</div>

我想通过div1div-main中选择&lt;p&gt;。假设我有div2而不是div1。在这种情况下,我如何选择&lt;p&gt;div-main

我试过了:

div1+div-main p{}

但它应该不起作用。那里有任何工作功能吗?

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    HTML

        <body>  
       <div class="div1">
           <p>Hello There</p>
        </div>
        <div class="div-main">
           <p>Hello There</p>
        </div>
        </body>
    

    CSS

        <style>
        .div-main p {
            color:Blue;
        }
        </style>
    

    https://www.w3schools.com/code/tryit.asp?filename=FEVSB2EMHKLD

    【讨论】:

      【解决方案2】:

      首先,类选择器必须以点“.div-main”和“.div1”开头。代码:

      .div1+.div-main p {
        color:red;
      }
      
      .div2+.div-main p {
        color:green;
      }
      <div class="div1">
         <p>next red</p>
      </div>
      <div class="div-main">
         <p>Hello There</p>
      </div>
      
      <div class="div2">
         <p>next green</p>
      </div>
      <div class="div-main">
         <p>Hello There</p>
      </div>
      
      <div class="div-main">
         <p>Green ? no!</p>
      </div>

      【讨论】:

        【解决方案3】:

        使用.div1 定位类div1

        使用~ 查找下一个.div-main

        使用&gt; 定位子p

        .div1 ~ .div-main > p{
        	color: red;
        }
        <div class="div1">
           <p>Hello There 1</p>
        </div>
        <div class="div2">
           <p>Hello There 2</p>
        </div>
        <div class="div-main">
           <p>Hello There Main</p>
        </div>

        【讨论】:

          【解决方案4】:

          使用.div-main &gt; p {...} 选择.div-main 元素内的p 标记

          但如果您只想选择那些直接跟在.div1 元素 (?) 之后的元素,请使用:

          .div1+.div-main p { color: red; }
          <div class="div1">
             <p>Hello There</p>
          </div>
          <div class="div-main">
             <p>Hello There</p>
          </div>

          【讨论】:

            猜你喜欢
            • 2011-10-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-10-10
            • 1970-01-01
            • 2021-10-03
            • 1970-01-01
            • 2018-03-11
            相关资源
            最近更新 更多