【发布时间】:2020-10-31 12:23:05
【问题描述】:
在以下代码笔中 - https://codepen.io/tanmaylodha/pen/MWKXJWW
CSS:第 26 行; left:50% 工作不正常。
但是如果我在绝对定位元素.badge 的包含块.section-first a 上设置display:inline-block,那么它工作正常。
<section class="section section-first">
<a href="#">
<h1 class="badge">Recommended</h1>
<h1 class="plus-plan">Our PLUS Plan</h1>
<h2>The most popular choice of our customers.</h2>
<p>
Benefit from increased storage and faster support to ensure that
your mission-critical data and applications are always available!
</p>
</a>
</section>
.section {
color: #6c6164;
background-color: #f7fafd;
padding: 1.563rem;
margin-bottom: 1.563rem;
border: 5px solid #fca156;
margin-right: 12.5rem;
box-shadow: inset 5px 5px 10px 2px #4fbf99;
}
.section-first {
margin-top: 8rem;
}
.section-first a {
position: relative;
}
.badge {
font-family: "Red Hat Display";
background-color: #60a7bd;
padding: 0.625rem;
border-radius: 5px;
margin: 0%;
position: absolute;
left: 50%;
}
.section h1.badge {
color: white;
}
.section-first .plus-plan {
margin-top: 50px;
}
.section-highlighted {
margin-left: 200px;
margin-right: 0px;
box-shadow: inset 5px 5px 10px 2px #4fbf99, 5px 5px 10px 2px #60a7bd;
text-align: right;
}
.section:hover {
border-color: #ff943c;
}
.section a {
text-decoration: none;
}
现在检查这个代码笔 - https://codepen.io/tanmaylodha/pen/jOWKyZP
但这里的结果是不同的。 .child 被绝对定位的元素在其包含块 .parent 的 50% 宽度之后得到正确定位@
<a href="" class="parent">
I am a Parent
<div class="child">
I am a child
</div>
</a>
.parent {
position: relative;
background-color: chocolate;
}
.child {
position: absolute;
background-color: darkgreen;
left: 50%;
}
在上述两个Codepen中,包含块(相对定位)总是一个内联元素,那为什么结果不同呢?
【问题讨论】:
-
请在此处发布您的minimal reproducible example -- 不要在 codepen 上
-
但是我只在codepen中包含了必要的html和css。
-
我不确定我是否知道技术解释,但不同之处在于,在第二个示例中, 标签有一些实际内容(“我是父母”)。如果您在第一个示例中执行相同操作,它应该可以工作。此外,此内容位于绝对定位的 div 之前也很重要。如果将 的第一个子元素更改为内联元素,它也可以工作。
-
@TanmayLodha 也在这里发布必要的代码,不仅仅是在 codepen 中。
-
您在锚定父级中没有任何内容可让子级定位在 50% 的位置。输入一行文字,您将看到“推荐”按预期移动。在您的第二支笔中,如果您取出文本“我是父母”,那么您的子块将不再位于它所在的位置
标签: css css-position inline absolute