当php

时间:2019-03-06 22:31:30

标签: php html css wordpress

我正在一个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);

3 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

<?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);
}

答案 1 :(得分:1)

要让PHP控制CSS,您需要向CSS可以定位的DOM输出一条新规则。

在这种情况下,您可以通过在没有内容的情况下简单地<h1>删除所需的类名来将类添加到echo中。 esc_html()返回一个空字符串,因此您可以对""进行检查。

以下内容不存在时,以下代码添加一个类black

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

您可以在此处制作将所需规则应用于新选择器的CSS:

.black {
  background-color: rgb(0, 0, 0);
}

答案 2 :(得分:1)

您可以尝试

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

和CSS

.bg-class1{
background-color: #yourcolor
}
相关问题