【问题标题】:Selecting child elements with css attribute value selector [closed]使用 css 属性值选择器选择子元素
【发布时间】:2015-07-26 19:04:52
【问题描述】:

我正在尝试为任何父 div 中的任何 .header 子 div 设置样式,并将“recipes”作为其类。

我知道我可以得到.category-recipes .header,但它们会是一些父div,会根据用户所在的位置而改变。例如。类别页面上的“类别食谱”,或单个帖子页面上的“单页食谱”。

这是页面外观的简化版本

<div class="category-recipes">

  <div class="otherdiv"></div>
  <div class="otherdiv"></div>
  <div class="header"></div>

</div> <!-- end of category -->

我试过了,没用。

div[class*="recipes"] .header{
  margin-bottom: 40px;
}

是否可以使用这种选择器让孩子或父母加入?

【问题讨论】:

  • 不知道你的意思是会有几个div?那些在哪里?如果您使用 .category-recipes .header,它们不会在您当前的标记中受到影响
  • 你还没有关闭div
  • @ManojKumar 在不同的页面上,父类会有所不同。例如。单页食谱,类别食谱等
  • 使用 id 作为标题和食谱作为一个类

标签: css wordpress css-selectors


【解决方案1】:

这可行:https://jsfiddle.net/09zkqatx/

基本上,我已经按照您描述的方式完成了所有操作。

div div {
    width: 50px;
    height: 50px;
    border: 1px solid black;
}

div[class*="recipes"] .header{
  margin-left: 40px;
}

【讨论】:

  • 谢谢,不太确定我的有什么问题,但它适用于 div[id*="recipes"] .archive-header{ margin-bottom: 40px;必须将 div 从使用类更改为 id
【解决方案2】:
div[class*="recipes"] div[class*="header"]{
  margin-bottom: 40px;
}

是我从https://stackoverflow.com/a/2094554/4871483得到的东西的衍生

你可以只使用 JavaScript 并像这样选择

var parDivs = document.getElementsByClassName("category-recipes");
for(parDiv in parDivs){
    var child = parDiv.children[2];
}

并从 JavaScript 更改样式

【讨论】:

    【解决方案3】:

    你可以实现你想要的- 为“食谱”使用单独的通用类 例如,

    <div class="category-recipes recipes">
      <div class="otherdiv"></div>
      <div class="otherdiv"></div>
      <div class="header"></div>
    </div> <!-- end of category -->
    

    也适用于您的“单页食谱”,

    <div class="single-page-recipes recipes">
      <div class="otherdiv"></div>
      <div class="otherdiv"></div>
      <div class="header"></div>
    </div> <!-- end of single page -->
    

    以上代码,使用css-

    div.recipes > div.header {
        margin-bottom: 40px;
    }
    

    OR,如果不能添加通用类,可以用小JS sn-p来实现这个-

    var el = document.getElementsByClassName('header')[0];
    // first check if the parent node has class with text recipes
    if(el.parentNode.classList.toString().match(/recipes/)) {
        //get the first child with class header and then style it
        el.style.marginBottom = "40px"; 
    }
    

    查看 JSFiddle - http://jsfiddle.net/xLzagpmv/4/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2012-08-16
      • 2017-10-04
      • 2014-01-10
      相关资源
      最近更新 更多