调用PHP图像作为CSS背景图像:url


call PHP image as CSS background-image: url

我的html标记中有以下代码:

<div class="profile-img">
    <img src="<?php echo $user_meta['profilepicture'][0]; ?>" />
</div>

此代码生成个人资料图像或化身。

我想把它作为背景图像使用到CSS中。

这就是我试图使用的:

<div class="profile-img">
     <style type="text/css">
        .profile-img img { background-image: url('<?php echo $user_meta['profilepicture'][0]; ?>'); }
     </style>
</div>

我的CSS看起来是这样的:

.profile-img {
width: 90px;
height: 90px;
margin-left: auto;
margin-right: auto;
text-align: center;
padding-top: 15px;
}
.profile-img img {
width: 80px;
height: 80px;
padding: 5px !important;
background: #fff !important;
border: none !important;
border-radius:500px;
-moz-border-radius:500px;
-webkit-border-radius:500px;
background-position: center center;
}

我正在努力实现的是一个圆形的图像缩略图化身与比例裁剪的图像。

但是,我试图用来将图像调用到CSS中的代码似乎没有起到作用。

我哪里错了?

您必须添加此规则以删除将通过php解析的background-image属性。

.profile-img {
    background-image: url('https://www.gravatar.com/avatar/4ee102e4ae1b9ab69077f7c471365f69?s=128&d=identicon&r=PG&f=1');
    background-repeat: no-repeat;
    background-position: 50%;
    border-radius: 50%;
    width: 100px;
    height: 100px;
}
<div class="profile-img"></div>

所以你最后添加的html将是:

<div class="profile-img" style="background-image: url('<?php echo $user_meta['profilepicture'][0]; ?>');"></div>

如果你希望图像是背景图像,而不是IMG标签的一部分,并且你需要它是动态的,那么你需要更像这样的东西:

<div class="profile-img" style="background:url('<?php echo $user_meta['profilepicture'][0]; ?>') no-repeat center center #ffffff"></div>

这将把图像作为背景放在.profile img DIV中。然后你只需要设置DIV:的样式

.profile-img {
     width: 90px;
     height: 90px;
     margin: 0 auto;
     text-align: center;
     padding: 5px !important;
     border: none !important;
     -moz-border-radius:50%;
     -webkit-border-radius:50%;
     border-radius:50%; }

老实说,我还没有检查你的CSS,因为我不确定你在圆形状之外想要实现什么。我把你的边界半径改为50%,因为这会创建一个圆。

我不确定,但不久前我使用了一些css来为Web应用程序提供圆角。也许这会对你有所帮助:

.myImg img{
-webkit-border-radius: 30px 30px 30px 30px;
-moz-border-radius: 30px 30px 30px 30px;
border-radius: 30px 30px 30px 30px;
}

希望这能帮助

<script>
 var imageSrc = "<?php echo $user_meta['profilepicture'][0]; ?>";
 $('.profile-img').css('background-image',imageSrc);
</script>