首页 > 解决方案 > 当php中没有内容时更改背景颜色

问题描述

我正在一个 php/wordpress 网站上工作,我想在没有内容时隐藏背景颜色。

我正在使用的 php 代码是:

<div class="featured-block__content">
    <h1 class="featured-block__tag"><?php echo esc_html( explode('|',get_the_title())[1]); ?></h1>
</div>

上述html/php代码的css代码为:

.featured-block__content {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 85px;
    background-color: rgb(255, 255, 255);
    opacity: 0.831;
    z-index: 3;
    position: relative;
    bottom: 85px;
}

问题陈述:

我想知道我需要在上面的 php 代码中进行哪些更改,以便在 h1 标记内没有内容的地方,背景颜色应该是background-color: rgba(0, 0, 0, 0);

此时h1标签内有内容,背景色为background-color: rgb(255, 255, 255);

标签: phphtmlcsswordpress

解决方案


您可以使用以下内容:

<?php
    $h1_content = esc_html(explode('|', get_the_title())[1]);
?>

<div class="featured-block__content <?= trim($h1_content) === '' ? 'no-h1' : ''; ?>">
    <h1 class="featured-block__tag"><?= $h1_content; ?></h1>
</div>

使用以下附加 CSS:

.featured-block__content.no-h1 {
    background-color: rgba(0, 0, 0, 0);
}

推荐阅读