bryan
bryan

Reputation: 9399

Manipulating css using attr() and data tags

I have a div class like so:

<div class="website-wrapper" data-content="63%"></div>

I have javascript that changes the data-content:

$(this).children().closest('.website-wrapper').attr('data-content', (imageHeight/imageWidth*100)+"%");

And I have my css declaration like this:

.website-wrapper:after { padding-top: attr(data-content); display: block; content: ''; }

For some reason, I can't get the padding-top to work correctly. Is there something I doing wrong?

Upvotes: 0

Views: 58

Answers (2)

zgood
zgood

Reputation: 12611

If you include a wrapping div you could use that to set your padding-top to maintain you aspect ratio. Just set that wrapping div to position: relative; and the inner div with the background-image can be set to position: absolute; top:0; bottom: 0; left: 0; right: 0; in order to take up the full space of the containing div which is creating the aspect ratio.

HTML

<div class="outer">
  <div class="website-wrapper"></div>
</div>

CSS

.outer{
  position:relative;
}

.website-wrapper{
  background-image: url('https://placehold.it/800x450');
  background-repeat: no-repeat;
  background-size:contain;

  position:absolute;
  top:0;
  bottom:0;
  left: 0;
  right: 0;

  border:1px solid red;
}

JS

$(this).children().closest('.outer').css('padding-top', (imageHeight/imageWidth*100)+"%");

See this fiddle for a demo.

Upvotes: 0

t1m0n
t1m0n

Reputation: 3431

As far as I know attr works only with content property currently, so you can manipulate only it. You can see browser compatibility here and more detail info - https://developer.mozilla.org/en-US/docs/Web/CSS/attr

.website-wrapper:after {
  content: attr(data-content);
}
<div class="website-wrapper" data-content="Hello"></div>

Upvotes: 3

Related Questions