Dynamically set background image

I need to apply a background image to a div that is set dynamically. In this way, the editor loads the image on a specific page into a specific attribute, and then I catch that image and show it.

So I would 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 using not using style = "..."?

thanks

+6
source share
5 answers

You are approaching correctly, but I have changed something.

In css I would do the following:

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

And in HTML I would save only the URL.

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

Thus, on the server side it is 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 switching to your css.

+3
source

If you basically do not want to use the html style attribute, you can create many css classes with a description of the 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 the html generation will look like this:

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

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

+3
source
 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> 
+3
source

you may have css defined on the php side, so it will look like this:

 <?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> 
0
source

You can point to background.jpg for all users, but instead redirect this request to the backend (PHP?) (You are redirecting from .htaccess for apache). And in this function, you can check the location of the image that will exist if the user uploaded the image and then will return this binary string as JPEG. Then you can actually reference background.jpg in external CSS.

0
source

Source: https://habr.com/ru/post/986038/


All Articles