Bad CSS style attribute based practices

I was working on a project and I needed to point the background image to the center when I got an idea. What if I used a selector that I found if I was present style="background-image: url()"and added the necessary code to center the image. The idea of ​​adding CSS based on a style attribute seems like really bad practice, but when I thought about it more, maybe it could be used in a reset file. Since the selector is not specific, it should be easily overwritten, and it allows you to change the default background style for all divs style="background-image: url()".

I'm not sure how practical this is, but is this what has ever been done? Are there any issues that I am observing what this might cause? Perhaps this is unrealistic, but I thought it was interesting enough to start a discussion. See sample code below ...

div{
  display: block;
  height: 100px;
  width: 100px;
}

[style*=background-image]{
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
<div style="background-image: url(https://i.stack.imgur.com/RhYGF.png)"></div>
Run codeHide result
+4
source share
2 answers

I think it depends on your project. Will yours be used <div>only for this purpose? and will all background images be centered? If so, then this is probably good, but if you think that you will overwrite them for other elements in your project, this can cause problems when developing your application.

Why don't you try something like this:

<div class="center-image" style="background-image: url('https://i.stack.imgur.com/RhYGF.png')"></div>

.center-image {
  height: 100px;
  width: 100px;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

:

<div class="center-image-wrapper">
   <div style="background-image: url(path-to-img1)"></div>
   <div style="background-image: url(path-to-img2)"></div>
   <div style="background-image: url(path-to-img3)"></div>
</div>

.center-image-wrapper > div {
      height: 100px;
      width: 100px;
      background-size: cover;
      background-repeat: no-repeat;
      background-position: center;
}

, display:block div. div .

+3

div <div class="myclass">, :

.myclass [style*=background-image]
0

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


All Articles