Use data attribute to set background image of pseudo-element

Is there a convenient way to set the background image of a pseudo-element through data attributes?

I am trying to achieve something similar, but I want to be able to set the background image in the markup through my CMS:

.full-width {
  background-color: #ededed;
  width: 100%;
  position: relative;
  z-index: -1;
}
.full-width:after {
  content: '';
  display: block;
  position: absolute;
  width: 50%;
  height: 100%;
  left: 50%;
  top: 0;
  background-image: url(//unsplash.it/1080/1920);
  background-size: cover;
  background-position: left center;
  z-index: -1;
}
.full-width .container {
  z-index: 99;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<div class="full-width">
  <div class="container">
    <div class="row">
      <div class="col-xs-6">
        <h2>Test 123</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
      </div>
    </div>
  </div>
</div>
Run codeHide result

not a direct duplicate How can I use the data attribute to set the background image in CSS? because I'm talking about pseudo-elements. Thank you for connecting me with this, but I already knew about these methods.

+4
source share
2 answers

CSS attr, , attr content ( -).

, JavaScript, - , , attr background.

+2

. , . attr(), . . , background-image: attr('data-bg' 'url'), data-bg URL-.

, - - ( ) .

.full-width {
  background-color: #ededed;
  width: 100%;
  position: relative;
  z-index: -1;
}
.full-width:after {
  content: '';
  display: block;
  position: absolute;
  width: 50%;
  height: 100%;
  left: 50%;
  top: 0;
  background-image: attr('data-bg' 'url');
  background-size: cover;
  background-position: left center;
  z-index: -1;
}
.full-width .container {
  z-index: 99;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<div class="full-width" data-bg="//unsplash.it/1080/1920">
  <div class="container">
    <div class="row">
      <div class="col-xs-6">
        <h2>Test 123</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
      </div>
    </div>
  </div>
</div>
Hide result
+1

All Articles