两个元素的z-index无法按预期工作

时间:2018-05-29 18:26:13

标签: html css html5 css3

我遇到以下代码的问题,这是一个更大问题的简化。

你可以告诉我为什么:

.div_A {z-index: 10;} < .div_C {z-index: 20;}

为什么div_C内的按钮位于div_A后面?

我需要知道确切的原因,以便非常具体地将解决方案应用于我的更大问题。

如果您能为我提供修复的代码(尽可能减少更改),我们将非常感激。

&#13;
&#13;
.button {
	display: inline-block;
	color: #fff !important;
	background-color: #be1e2d;
	text-decoration: none;
	padding: 10px 23px;
}
.div_A {
	display: inline-block;
	position: absolute;
	top: -100px;
	z-index: 10;
}
.div_B {
	position: relative;
	display: inline-block;
	width: 400px;
	height: 400px;
	background-color: #aaf;
	opacity: 0.9;
}
.div_C {
	text-align: center;
	z-index: 20;
}
&#13;
<div>
	<div class="div_A">
		<div class="div_B"></div>
	</div>
	<div class="div_C">
        <a href="#" class="button" style="">TRY TO CLICK ME!</a>
	</div>
</div>
&#13;
&#13;
&#13;

谢谢!

2 个答案:

答案 0 :(得分:1)

对于position应用static的元素,您需要z-index以外的已设置position: relative;设置,以使其具有所需效果。我在snippe中将.button { display: inline-block; color: #fff !important; background-color: #be1e2d; text-decoration: none; padding: 10px 23px; } .div_A { display: inline-block; position: absolute; top: -100px; z-index: 10; } .div_B { position: relative; display: inline-block; width: 400px; height: 400px; background-color: #aaf; opacity: 0.9; } .div_C { text-align: center; z-index: 20; position: relative; }添加到下面的DIV_C中。

&#13;
&#13;
<div>
	<div class="div_A">
		<div class="div_B"></div>
	</div>
	<div class="div_C">
        <a href="#" class="button" style="">TRY TO CLICK ME!</a>
	</div>
</div>
&#13;
ViewComponentResult result =
        component.Invoke() as ViewComponentResult;
    int auditCount =
        ((IntDashMakeRecAssgnmntsPoRespMngrVM)result.Model).Audits.Count();
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

你只是忘了放位置:绝对;在.div_C

.button {
	display: inline-block;
	color: #fff !important;
	background-color: #be1e2d;
	text-decoration: none;
	padding: 10px 23px;
}
.div_A {
	display: inline-block;
	position: absolute;
	top: -100px;
	z-index: 10;
}
.div_B {
	position: relative;
	display: inline-block;
	width: 400px;
	height: 400px;
	background-color: #aaf;
	opacity: 0.9;
}
.div_C {
	text-align: center;
	z-index: 20;
	position: absolute;
}
<div>
	<div class="div_A">
		<div class="div_B"></div>
	</div>
	<div class="div_C">
        <a href="#" class="button" style="">TRY TO CLICK ME!</a>
	</div>
</div>