Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set background image

Tags:

html

css

php

I need to apply a background-image to a div that gets set dynamically. So the editor uploads an image on a specific page to a specific attribute and I catch this image then and display those.

Therefore I'd do something like this:

<div class="foo" style="background:url(<?php echo $attribute; ?>) no-repeat top right; background-size: 140px;">

Is there a better approach to it by not using style="..." ?

Thanks

like image 501
Daiaiai Avatar asked Apr 27 '15 07:04

Daiaiai


3 Answers

You approach is correct but I would change something.

In the css I would make this:

.foo {
    background-repeat: no-repeat;
    background-position: top right;
    background-size: 140px;
}

And in the HTML i would only keep the url.

<div class="foo" style="background:url(<?php echo $attribute; ?>);">

This way on the server-side it's easier to see where you have dynamic content. And you only need to change the url for the corresponding image.

So if later you work with another developer he knows exactly where he should change the images without going to your css.

like image 185
Joel Almeida Avatar answered Oct 05 '22 03:10

Joel Almeida


If you fundamentally don't want to use style html attribute, you could create many css classes with description of background-image property

.my-background { 
     background-repeat: no-repeat;
     background-position: top right;
     background-size: 140px
}
.my-background_custom2 {
     backgroud-image: url('/path/1/to/your/image.png') 
}
.my-background_custom2 {
     backgroud-image: url('/path/2/to/your/image.png') 
}

And html generation will look like:

<div class="foo my-background my-background-<?= $attribute ?>">

But if you choose this solution and number of css classes will be large I recommend you use style attribute despite your desire to refuse of this attribute

like image 21
ufocoder Avatar answered Oct 05 '22 03:10

ufocoder


you can use this  html & php code:

HTML:
<style type="text/css">
.bannar {    
    width: 100%;
    height: 361px;
    background: no-repeat center;   
}
</style>

PHP:

<div class="bannar" 
style="background-image: url('<?php echo $this->webroot . 'companyImages/bannar' . '/' . $company_page[0]['companypages']['bannar']; ?>')">
</div>
like image 22
Omar Faruk Avatar answered Oct 05 '22 04:10

Omar Faruk