z-index和边界是否有特殊性,我从未听说过?

时间:2014-09-19 14:36:56

标签: css

我试图使用margin和z-index(es)在某些文本的任一侧创建一条线,但z-index似乎并没有像我预期的那样对元素进行排序。最后,我想将文本背景设置为白色,并且只显示任意一侧的线条。我可以让线条在盒子后面,但不能在盒子和文本之间。任何人都可以为我解释一下吗?我把头发撕掉了,我的头发不多。



.thebox {
    background-color: white;
    color: black;
    padding-top: 30px;
    padding-bottom: 30px;
    z-index: 1;
}

.thebox h1 {
    text-align: center;
    background-color: #666;
    margin-right: 100px;
    margin-left: 100px;
    font-size: 16px;
    z-index: 10;    
}

.thebox .theline {
	border-top: solid 1px black;
	width: 100%;
	height: 1px;
	position: absolute;
	top: 19%;
	z-index: 5;
}

<div class="thebox">
    <h1>This is my title text.  I'm hoping that it should end up with a line either side, but not overwriting it.</h1>
    <div class="theline"> </div>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

我删除了位置属性并切换了订单,现在应该没问题了:

http://jsfiddle.net/4cw9ns8q/2/

.thebox .theline {
  border-top: solid 1px black;
  width: 100%;
  height: 1px;
  top: 19%;
  z-index: 5;
}

答案 1 :(得分:0)

尝试以下方法。您需要在各种元素上设置position: relative,以使z-index生效。否则,你走在正确的轨道上。

&#13;
&#13;
.thebox {
    background-color: yellow;
    color: black;
    padding-top: 30px;
    padding-bottom: 30px;
    position: relative;
}

.thebox h1 {
    text-align: center;
    background-color: #666;
    margin-right: 100px;
    margin-left: 100px;
    font-size: 16px;
    position: relative;
    z-index: 10;    
}

.thebox .theline {
    border-top: solid 1px black;
    width: 100%;
    height: 1px;
    position: absolute;
    top: 50%;
    z-index: 5;
}
&#13;
<div class="thebox">
    <h1>This is my title text.  I'm hoping that it should end up with a line 
        either side, but not overwriting it.</h1>
    <div class="theline"> </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您还需要在h1中添加绝对位置:

.thebox {
background-color: white;
color: black;
padding-top: 30px;
padding-bottom: 30px;
z-index: 1;

}

.thebox h1 {
text-align: center;
background-color: #666;
margin-right: 100px;
margin-left: 100px;
font-size: 16px;
z-index: 10; 
display:inline-block;
position:absolute;

}

.thebox .theline {
border-top: solid 1px black;
width: 100%;
height: 1px;
position: absolute;
top: 39%;
z-index: 5;

}

默认位置值是静态的,index-z仅适用于具有非静态位置的元素