【问题标题】:Is it possible to add margin between parent divs depending on child class with pure CSS? [duplicate]是否可以根据具有纯 CSS 的子类在父 div 之间添加边距? [复制]
【发布时间】:2022-01-05 07:33:41
【问题描述】:

我有多个 <div> 包装了一些具有 class 的孩子。但问题是父<div> 没有classid。是否可以在包装父 div 之间添加 margin-bottom,它有一个特定的 child 与纯 CSS 还是我需要使用 jQueryJS 来实现这一点?

HTML 的外观示例:

// parent 
    <div> 
    // children
       <h2 class="child-class-1" ></h2>     
       <p class="child-class-2" ></p>
    </div>
    
    // margin-bottom between the wrapping parent divs
    
    <div>
       <h2 class="child-class-1" ></h2>    
       <p class="child-class-2" ></p>
    </div>

我找到了一个纯 CSS 的解决方案。

解决方案:

div > .child-class-1, .child-class-2 {
margin-bottom: 80px;
}
   <div style="background-color:red; height: 400px; width:400px;"> 
       <h2 class="child-class-1" ></h2>     
       <p class="child-class-2" ></p>
    </div>
    
    <div style="background-color:red; height: 400px; width:400px;">
       <h2 class="child-class-1" ></h2>    
       <p class="child-class-2" ></p>
    </div>
    
        <div style="background-color:red; height: 400px; width:400px;">
       <h2></h2>    
           <p>Dosent affect the div which dosen't have the child class</p>
    </div>

【问题讨论】:

标签: javascript html jquery css


【解决方案1】:

也许您可以使用外部/内部样式在 HTML 中为 &lt;div&gt; 标签添加属性,但这会影响当前/所有 html 页面中的所有标签

CSS 代码示例:

div {
  margin-bottom: 12px
}

或者您可以只为一个 &lt;div&gt; 添加自定义样式,仅使用内联样式,您可以使用:

<div style="margin-bottom:12px">
     <h2 class="child-class-1" ></h2>    
     <p class="child-class-2" ></p>
</div>

但这很麻烦,因为您的 HTML 中有另一个 &lt;div&gt;

【讨论】:

    猜你喜欢
    • 2017-03-16
    • 2018-03-09
    • 2018-01-18
    • 2013-06-12
    • 2015-02-12
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多