I am using JavaScript/jQuery to populate a date field on my page. I want to add CSS styling to each individual character of the generated date and wondering if it is possible and how I could go about doing it. Basically, I want the end result to look like this:
Here is my code which is generating the date:
HTML:
<div class="date"></div>
JavaScript:
var monthNames = [ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ];
var dNow = new Date();
var date = (monthNames[dNow.getMonth()]) + ' '
+ ('0' + dNow.getDate()).slice(-2) + ' '
+ dNow.getFullYear();
$('.date').text(date);
Here's a JSFiddle.
I am not sure if OP is asking for a means to split the characters into its own self-containing element only, or also for the CSS solution that approximates the screenshot. My answer does both — see demo fiddle here: http://jsfiddle.net/teddyrised/pv9601hj/4/
For splitting the date string, you will have to rely on JS, something like:
var monthNames = [ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ];
var dNow = new Date();
var date = (monthNames[dNow.getMonth()]) + ' '
+ ('0' + dNow.getDate()).slice(-2) + ' '
+ dNow.getFullYear();
var dateSplit = date.split("");
$('.date').html('<span>'+dateSplit.join('</span><span>')+'</span>');
For the CSS, it is simply a clever use of CSS3 flexbox specification and pseudo-elements:
.date {
background-color: #000;
display: flex;
}
.date span {
border-radius: 4px;
box-shadow: inset 0 0 1px 2px rgba(255,255,255,.125);
color: #fff;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 2em;
line-height: 2em;
margin-right: 4px;
overflow: hidden;
position: relative;
width: 1em;
height: 2em;
text-align: center;
}
.date span::before {
background-color: rgba(255,255,255,.2);
content: '';
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 1px;
}
.date span::after {
background-image: linear-gradient(
to bottom,
rgba(0,0,0,.1) 0%,
rgba(0,0,0,.25) 50%,
rgba(255,255,255,.25) 50%,
rgba(255,255,255,.1) 100%
);
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
It's not possible to apply CSS to individual characters, only to elements. Therefore, you need simply to split your characters into elements! Wrap each character in a span
, and you can apply CSS to each of those spans
(each of which contains just one character).
Something like this (full JSFiddle):
var chars = date.split("");
$.each(chars, function(i, char) {
$(".date").append("<span>" + char + "</span");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With