当div有第二个孩子使用css时,删除第一个子填充

时间:2018-03-15 01:25:36

标签: html css twitter-bootstrap

我在一个div中有两个锚标签。我想仅在div有一个锚标记时才应用填充样式。例如,集合2,不应显示填充

.email a {
  padding-top:10px;
  display: block;
} // for set 1

//I need to remove padding for a tag when div having two a tag like set 2
    Set 1:
    <div class="email">
      <a href="#">Hello</a>
    </div>
    Set 2:
    <div class="email">
      <a href="#">Hello</a>
      <a href="#">Hello</a>
    </div>

4 个答案:

答案 0 :(得分:4)

使用only-child选择器:

.email a {
  display: block;
}

.email a:only-child {
  padding-top: 10px;
}
Set 1:
<div class="email">
  <a href="#">Hello</a>
</div>
Set 2:
<div class="email">
  <a href="#">Hello</a>
  <a href="#">Hello</a>
</div>

答案 1 :(得分:1)

使用css的:only-child选择器可以实现此目的!例如,

.email a:only-child{
  padding-top:10px;
  display: block;
}

答案 2 :(得分:0)

&#13;
&#13;
.email a {
  padding-top:10px;
  display: block;
} 

.email:not(:first-child) a{
  padding-top: 0;
}
//I need to remove padding for a tag when div having two a tag like set 2
&#13;
Set 1:
    <div class="email">
      <a href="#">Hello</a>
    </div>
    Set 2:
    <div class="email">
      <a href="#">Hello</a>
      <a href="#">Hello</a>
    </div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

试试这个:

.email > a:not(:only-child):first-child { padding-top:0px}

显然,您可以在那里调整CSS以调整.email类的原始样式

你可以在这里看到一个有效的小提琴:https://jsfiddle.net/37js9wae/3/

&#13;
&#13;
.email a {
  padding-top:30px;
  display: block;
}

.email > a:not(:only-child):first-child { padding-top:0px}
&#13;
Set 1:
    <div class="email">
      <a href="#">Hello</a>
    </div>
Set 2:
    <div class="email">
      <a href="#">Hello</a>
      <a href="#">Hello</a>
    </div>
&#13;
&#13;
&#13;