如何使 <p> 不继承 <span> 不透明样式?

How to make a <p> not to inherit the <span> opacity style?

我正在尝试制作一个带有圆角并带有一点透明度的白色按钮。文字不应该是透明的。我尝试将 opacity: initial 用于 <p> 样式,但它似乎不起作用。看看我的代码片段以更好地理解。

body {
  background-color: #264D38;
 }

.button {
 display: inline-block;
 width: 150px;
 border-radius: 2px;
 margin-top: 20px;
 margin-bottom: 20px;
 background-color: #898989;
 opacity: 0.4;
 filter: alpha(opacity=40); /* Para IE8 e anteriores */
}

span.button > p {
 opacity: initial;
 padding: 10px;
 color: #ffffff;
 font-weight: bold;
    text-align: center;
}

.button:hover {
 background-color: #000000;
}
<body>
<a href="#"><span class="button"><p>BUY NOW</p></span></a>
</body>

您可以使用 RGBA 值作为背景颜色,而不是使用不透明度。

例子

.button {
    display: inline-block;
    width: 150px;
    border-radius: 2px;
    margin-top: 20px;
    margin-bottom: 20px;
    background-color: rgba(137,137,137,.4);
}

首先,使用正确的代码结构。 span 是一个内联类型,必须在 p 元素中,这是一个块类型,因为@hungerstar 说它不会是一个有效的标记。

然后你可以这样做,用:before伪元素设置span的背景和绝对位置:

See it here

不透明度影响所有 children 元素。 Children 不能有 0% 的透明度,而 parent 有 40%。

其他解决方案仅设置 semi-transparent 背景。

body {
    background-color: #264D38;
}

.button {
    display: inline-block;
    width: 150px;
    border-radius: 2px;
    margin-top: 20px;
    margin-bottom: 20px;
    background-color: rgba(255, 255, 255, 0.1);
}

span.button > p {
    padding: 10px;
    color: #ffffff;
    font-weight: bold;
    text-align: center;
}

.button:hover {
    background-color: rgba(0, 0, 0, 0.2);
}
<body>
    <a href="#">
        <span class="button">
            <p>BUY NOW</p>
        </span>
    </a>
</body>

您可以使用 RGBA or HSLA 作为您的 background-color。您可以改进您的标记,使其不再无效(您用内联元素 <span> 包装块级元素 <p>)。我们现在少了一个具有相同结果的元素。

Support chart 对于 rgba()hsla()

<a href="#"><span class="button">BUY NOW</span></a>
body {
  background-color: #264D38;
 }
.button {
    display: inline-block;
    width: 150px;
    padding: 26px 0;
    border-radius: 2px;
    margin-top: 20px;
    margin-bottom: 20px;
    background-color: rgba( 137, 137, 137, 0.4 );
    color: #FFF;
    font-weight: bold;
    text-align: center;
}
.button:hover {
    background-color: #000;
}

演示 JSFiddle.