Reputation: 2200
I was working on a project, and I needed to tell a background image to center, when I got an idea. What if I used a selector that found if style="background-image: url()"
was present and added the necessary code to center the image. The idea of adding CSS based on the 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 that specific it should be easily overwritten, and it allows the default background style for all divs with style="background-image: url()"
to be changed.
I am not sure how practical this is, but is this something that is ever done? Are there any issues I am overseeing that this could cause? Maybe this is not realistic, but I thought it was interesting enough to start a discussion on. See example 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.sstatic.net/RhYGF.png)"></div>
Upvotes: 4
Views: 337
Reputation: 3099
I think it depends on your project. Will all your <div>
s only be used for this purpose? and will all your background images be centered? If so, then maybe it's fine, but if you think you'll be overwriting them for other elements in your project then it might cause issues down the road as you develop your application.
Why don't you try something like this:
<div class="center-image" style="background-image: url('https://i.sstatic.net/RhYGF.png')"></div>
.center-image {
height: 100px;
width: 100px;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
or if you have multiple ones in one section:
<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;
}
Also side note that you don't need to apply display:block
to a div. div is already a block element.
Upvotes: 3
Reputation: 90
Give a class to the div like <div class="myclass">
and then apply styling like this:
.myclass [style*=background-image]
Upvotes: 0