Sunday, November 1, 2015

Pulling your data attributes using CSS pseudo property

I learned this recently and have been using it frequently, getting the html data attributes to content using css pseudo properties.

In this article, we will actually see how to control position of an element using css and also getting the data attribute using css content property.





How to do it ?


HTML element attribute data-somevalue, css pseudo property content: attr(somevalue);


Clear Example to get data attribute with css pseudo property

Create simple HTML doc with two images


Lets say we have two images in the store that needs to be labelled, one is NEW and other is TRENDING. Wrap those items in a div holder/panel and add a data attribute TYPE to that panel

<div class="panel" data-type="new">
 <img src="https://images.unsplash.com/photo-1444703686981-a3abbc4d4fe3?fit=crop&fm=jpg&h=725&ixlib=rb-0.3.5&q=80&w=1300">
</div>
   
    <div class="panel" data-type="trending">
 <img src="https://images.unsplash.com/photo-1443926818681-717d074a57af?fit=crop&fm=jpg&h=725&ixlib=rb-0.3.5&q=80&w=1300">
</div>


Add below css to it.


If you observe the below css, I added position:relative to the panel, and position:absolute to the pseudo element, with this I get complete control over the pseudo element position, now I can control it using top, right, bottom, left etc...

img {
  width:100%;
}
.panel {
  position: relative;
  display: inline-block;
  width:350px;
}

.panel:after {
  content: attr(data-type);
  z-index: 99999;
  color:#ff6600;
  display: block;
  top:1px;
  right:1px;
  padding:3px 5px;
  border-radius:3px;
  background: white;
  position: absolute;
}



Fiddle for the above example is available here. http://jsfiddle.net/mannemvamsi/x89dgccb/

Checkout:

Removing default browser styles

Making navigation of google apps style 

More Jquery plugins and javascripts

No comments:

Post a Comment