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
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.
you can have the css defined in the php side so it will look like that:
<?php
$backgroundCss = '<style>#uniqueback{
background:url('.$attribute.') no-repeat top right; background-size: 140px;
};</style>';
?>
<html>
<head>
<?php echo $backgroundCss;?>
</head>
<body>
<div id="uniqueback" class="foo" ></div>
</body>
</html>
You could point to background.jpg, for all users, but redirect that request to a backend (PHP?) function instead (you redirect with .htaccess for apache). And in this function you could check the location of the image that would exist if the user had uploaded an image, and then return this binary string as a JPEG. Then you could actually link to background.jpg in the external CSS.
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
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>