div上的可选底部边框

时间:2013-08-09 16:36:22

标签: css3

我有两个HTML示例...基本上信息div中总是有一个名称div,但总数可能更多。

1)

<div class="person">
    <div class="info">
        <div class="name">Isabelle  of_Bavaria</div>
    </div>
</div>

2)

<div class="person">
    <div class="info">
        <div class="name">King of France Charles_V  the_Wise</div>
        <div class="title"><label>Title:</label>King of France</div>
        <div class="date"><label>Birth:</label>Jan 21st, 1337</div>
        <div class="date"><label>Death:</label>Sep 16th, 1380</div>
    </div>
</div>

我正在使用这一点CSS在名称下面添加一行以及在div div周围添加一个框。

.person .name
{
    position: relative;
    text-align: center;
    border-bottom: 1px dotted black;
}

.person
{
    position: relative;
    width: 250px;
    height: auto;
    border: 1px solid black;
    margin-top: 5px;
    padding: 5px;
}

我可以用css做些什么来阻止名称在样本1中留下边框,而不需要额外的类或div吗?

2 个答案:

答案 0 :(得分:2)

尝试在 .person .name 条目的顶部添加这段CSS

.person .name:only-of-type
{
    border-bottom: 0px transparent;
}

这条CSS意味着如果在.person中只有使用.name类的元素类型之一(在这个例子中它是一个div),它将没有底部边框。你必须把它放在 .person .name 之前才能覆盖它。

编辑:

在考虑了一点之后,我认为伪类:only-child 更适合您的需求,而不是:only-of-type 它仅适用于 .name .person 的唯一子项。所以这是更新的CSS

.person .name:only-child
{
    border-bottom: 0px transparent;
}

答案 1 :(得分:0)

逻辑上像这样的东西?

.person > .info[having more than one div child] > .name
{
    border-bottom: ...
}
遗憾的是,我认为没有[...]选择器,但是,有“相邻的兄弟选择器”(http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors

也许正如@PhilPerry建议的那样,你可以将概念改为“在第一个孩子(或名字)之后立即在div上设置一个上边框”,如下所示:

.name:first-child + div
{
    border-top: ...
}
相关问题