Calling a class with symbolic name - html

EDIT: I would like to implement it with Jekyll, which (as far as I know) does not have PHP, jQuery, and so on...
I have a simple problem with CSS; it must have a simple solution but I just don't find it.
Suppose one has multiple divs with some classes:
<div class="cat">
<div class="dog">
<div class="bird">
<div class="snake">
...
and in a .css we want to style these 'pet' divs; the style is very similar from class to class (for instance we have some photos cat.jpg, dog.jpg... and want to show them). Can this be achieved by a somewhat symbolic method? Something like
div.pet{
width: 50px;
height: 50px;
background: url("/pictures/pet.jpg") no-repeat 0 0;
...
(but there is no class="pet" nor pet.jpg)

I would use sass:
div {
$list: "cat", "dog", "frog";
// generate classes for list elements
#each $element in $list {
&.#{$element} {
background-image: url('images/#{$element}.jpg');
}
}
}

That's not something you can do with CSS. CSS can only style objects and can't make other changes/additions/deletions of DOM objects.
But it is definitely something you can do with jQuery! If you know that you always have a class name class="cat" that is the same as the file name cat.jpg, you can do something like this:
$("div").each(function(){
var petClass = this.attr('class');
var petImg = petClass + ".jpg";
this.append("<img src='"+petImg+"' ... >");
});

Im not sure what your asking But as far as I understand you want to have some global setting for div elements and change the background image:
https://jsfiddle.net/shtjab2k/
Css
#pets > div
{
width:100px;
height:40px;
border:2px solid black;
float:left;
}
.cat
{
background-image: url("https://i.vimeocdn.com/portrait/58832_300x300.jpg");
}
.bird
{
background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Solid_blue.svg/2000px-Solid_blue.svg.png");
}
html
<div id="pets">
<div class="cat "></div>
<div class="dog "></div>
<div class="bird "></div>
<div class="snake "></div>
</div>

The simplest, pure-css way to do this is this:
.dog, .cat, .bird, .snake {
width: 50px;
height: 50px;
background: url("/pictures/pet.jpg") no-repeat 0 0;
}
It doesn't matter that the background we provide doesn't exist, we'll replace it in the css for individual pet types:
.dog {
background-image: url("/pictures/dog.jpg");
}
It seems like you're looking for a way to do this in a single ruleset, which, unfortunately, is not possible. For that, you'd have to look into using Javascript or a CSS superset (see other answers on this post).
Otherwise, you can just write a couple more lines of css and set the background image for each pet type. =P

It isn't possible to add different images sources to the image tags with pure CSS. You may need to use JS, JQuery, PHP , etc.
You may do this using JavaScript/JQuery as follows :
Store all the image names in an array and then run a loop on-load(of page) to get images by using those array element(values).
Using jQuery, you may set img source like this:
$("img:nth-child(i)").attr('src', <new path from array[i th element]>);
The nth-child(i) means ith image.
Using Js, you may do this:
var images = [
'path/to/image1.png',
'path/to/image2.png',
'path/to/image3.png',
'path/to/image4.png',
'path/to/image5.png'
];
function loadImages(imgArr, targetId){
for(var i=0; i< imgArr.length; i++) {
console.log(imgArr[i]);
var img = new Image();
img.src = imgArr[i];
document.getElementById('output').appendChild(img);
}
}
loadImages(images);
You can also invode the loadImage() function from yout button:
<button onclick="loadImages(images)">Start</button>
Refer : JavaScript load Images in an Array

Related

CSS set background image regarding class selector

I would like to set the background image of a div regarding its class. The web I am developing should show a set of game cards. Each card is contained in a div and have a class like this:
<div class="card value suit>
</div>
Being the suit and value for instance clubs and five respectively. So for instance, for a div container like this:
<div class="card seven clubs>
</div>
I wonder if there is a way via CSS to set its background-image to this attribute without writing this for each card:
.card.seven.clubs {
background-image: url("../../images/seven_clubs.png");
}
you can't really have dinamy classes with css only, you need some form or precompiler such as SASS to to convert from thing like
for every number do {
generate number properties
}
for every suite do {
generate suite css properties
}
to actual css code in the form of
.suite1{
property: value;
}
.suite2{
property:value
}
.number1{
property:value
}
or you can use Javascript and dynamically set styles on it
var cards = document.getElementsByClassName('card');
for (var i = 0; i++; i < cards.length){
var thisElementClasses = cards[i].classList;
let imageUrl = '../../images/'+thisElementClasses[0]+'_'+'thisElementClasses[1]'+'.png';
card[i].style.backgroundImage = imageUrl;
}

Pass a value from HTML to CSS

I was interested whether can I pass value to the css class from the html?
Like this
Example:
<div class="mt(5)"> Some text </div>
style {
.mt(#mpx) {
margin-top: #mpx px;
}
}
I've heard that such way was possible in Less
No, the way you want it is impossible in either CSS or any of its supersets (like Less and others). It's always HTML that uses values from CSS and not in opposite. Thus you'll need some scripting for what you need.
You can however pass values from HTML to CSS via Custom Properties using inline styles:
.c {color: var(--c)}
.m {margin: var(--m)}
<div class="c" style="--c: blue" >Foo</div>
<div class="m" style="--m: 0 2em">Bar</div>
<div class="c" style="--c: green">Baz</div>
Or even like this:
* {
color: var(--c);
margin: var(--m);
/* etc. */
}
<div style="--c: blue" >Foo</div>
<div style="--m: 0 2em">Bar</div>
<div style="--c: green">Baz</div>
But that method is no way different from styling by the plain vanilla method, i.e.:
<div style="color: blue">
... etc.
It is essentially same ugly and non-maintainable.
Many people try to achieve the goal by generating hundreds of predefined classes like .mt-1, .mt-2, ... .mt-99 etc. (since it's extremely easy thing to do in a CSS-preprocessor). But it's even more ugly solution (I won't bother you with details on why it is so. You'll read about that elsewhere or learn yourself after a few projects).
Maybe this is what you looking for? CSS: Attr()
You can bind the value to an attribute and then get this attribute back in the css, like this:
CSS
<p data-foo="hello">world</p>
CSS
[data-foo]::before {
content: attr(data-foo) " ";
}
Result
hello world
Here is a way of doing that without the use of LESS.
Use CSS variables:
Variables can be declared in the style attribute of the HTML elements.
Then, the CSS will catch the values from the HTML and apply the correct styles.
Add some JavaScript:
The values of the variables can now be dynamically modified.
⋅ ⋅ ⋅
Example of use:
Background color is set in the HTML, (fixed)
Padding of div1 will grow if clicked. (dynamic)
// When clicking on the div1, padding is gonna grow up.
document.getElementById("div1").onclick = function(){
var pad = this.style.getPropertyValue("--pad");
this.style.setProperty("--pad", parseInt(pad) + 1);
}
.divs {
background: var(--bg);
padding: calc(var(--pad)*5px);
}
<div id="div1" class="divs" style="--bg: #ff6; --pad: 1;">div1</div>
<div id="div2" class="divs" style="--bg: #f66; --pad: 2;">div2</div>
⋅ ⋅ ⋅
About CSS variables:
The variable names must begin with -- and are case sensitive.
These variables values are applied to the element and its children.
To use it globally, you can declare it on the body tag.
Here is a link with some examples: https://www.w3schools.com/css/css3_variables.asp

Change app-header background image using databinding

I'm newbie to web, and sorry for not good English.
But I have question.
I want to change Polymer's app-header element background image using databinding.
I want to show different header image whenever router's page changed.
But this code is not working.
I don't know how to pick and manipulate css of background-image.
<style>
...
--app-header-background-front-layer: {
/*This line is working*/
/*background-image: url(/images/tmp/header_image_1.png);*/
/*This line is NOT working*/
background-image: url([[headerImageUrl]]);
background-position: left center;
};
...
</style>
<script>
...
properties: {
...
headerImageUrl: {
type: String,
value: "/images/tmp/header_image_1.png"
}
...
},
...
<script>
I got my solution.
Niklas Lang gave me a hint.
Here is my code.
<style>
...
:host {
...
/*this custom css property could be changed whenever I want */
--header-image: url(/images/tmp/header_image_1.png);
...
}
...
--app-header-background-front-layer: {
background-image: var(--header-image);
background-position: left center;
};
...
</style>
<script>
...
// this function called when router's page value is changed.
setHeader: function () {
switch (this.page) {
case blabla1:
this.customStyle['--header-image'] = 'url(/images/tmp/header_image_1.png)';
this.updateStyles();
break;
case blabla2:
this.customStyle['--header-image'] = 'url(/images/tmp/header_image_2.png)';
this.updateStyles();
break;
case blabla3:
this.customStyle['--header-image'] = 'url(/images/tmp/header_image_2.png)';
this.updateStyles();
default :
break;
}
},
...
<script>
I think you are missing the actual Element in your style.
When you make use of Polymer mixin you should apply it to the corresponding Element, in your case the app-header.
app-header {
--app-header-background-front-layer: {
background-image: url();
};
}
However, i am not sure if it is even possible to bind to your style.
What you could try is to bind to Inline style.
In the Polymer documentation they call it Bind to a target attribute
<div style$="color: {{myColor}};">
But in your case I am not entirely sure how this is supposed to work as you are applying mixin and not just a single style value.

Can i use attributes of element to create style rules?

I'm noot good in english, so the title may seem a bit odd.
I want to use css function attr() like this:
I mean i have a container <div> and an inner <div> that i want to have width depending on data-width attribute. For example this would be great, but this doesnt work:
<div class="container">
<div data-width="70%">
</div
</div>
.container {
width: 600px;
height: 200px;
}
.container div {
width: attr(data-width);
height: 100%;
}
Is there any noJS way to use attributes like that?
UPDATE: Guys convinced me that the JS is the only way to do this :)
That's not a big problem (but that's bad. CSS, why youre so illogical? Is the difference between content:attr(data-width) and width: attr(data-width) so big ?).
One of the guys had an idea to go through the all elements with jQuery.
That's ok, but it is very... local? Don't know how to say it in english.
Anyway, i remaked his code a little bit and here it is:
allowed = ['width','color','float'];
$(document).ready(function () {
$('div').each(function (i, el) {
var data = $(el).data(),style = '';
if (!$.isEmptyObject(data)) {
$.each(data, function (attr, value) {
if (allowed.indexOf(attr) != - 1) {
style += attr + ': ' + value + '; ';
}
})
if (style.length != 0) {
$(el).attr('style', style);
}
}
})
})
Idea is simple:
1. We suppose that style we want to add to an element is the only one. I mean there are no scripts that will try to add some other styles,
2. We create an array of allowed attribute names, we need to avoid using wrong names at the style attribute, for example style="answerid: 30671428;",
3. We go through each element, save its data attributes in an object, check if object is empty, and if not - check every attribute if it is allowed, create a string that contains all styles that we need, and - finally - add our style string to the element as the content of style attribute.
That's all, thanks everybody
I would not advise to use CSS alone since it will not allow you to do what you're looking for... instead use a scripting language (in my case jQuery) to accomplish this functionality for you like so: jsFiddle
jQuery
jQuery(document).ready(function(){
var dataElem; // to store each data attribute we come accross
jQuery('div').each(function(){ //loop through each div (can be changed to a class preferably)
dataElem = jQuery(this); //get the current div
if(dataElem.data('width')){ //make sure it exists before anything further
dataElem.width(dataElem.data('width')); //set the element's width to the data attribute's value
dataElem.css("background-color", "yellow");
}
});
});
HTML
<p>The links with a data-width attribute gets a yellow background:</p>
<div>
w3schools.com
</div>
<div class="me" data-width="50"> <!-- change value to see the difference -->
disney.com
</div>
<div>
wikipedia.org
</div>
Notes on the above:
each, data, width.
Instead of doing data-width, use a class attribute. An html tag can have mutliple classes separated by spaces, so if you wanted to be very precise, you could set up as many classes as you need. For instance:
<div class="w70 h100">
</div>
Then in your css:
.w70{
width: 70%;
}
.h100{
height: 100%;
}
And so on.
Is there any noJS way to use attributes like that?
No, you cannot use CSS to set the width of the element to it's data-width attribute. CSS does not allow for this as attr() is only currently available for the CSS content property which is only available on css pseudo elements (::before and ::after).
How can you achieve this with as little javascript as possible?
This is extremely easy to do using the native host provided DOM API.
Select the elements using Document.querySelectorAll().
Iterate the elements and apply the styles using Element.style which can be retrieved from the data-width attribute using Element.dataset
(Demo)
var items = document.querySelectorAll('#container div'), item, i;
for(i = 0; (item = items[i]); i++) item.style.width = item.dataset.width;

HTML/CSS: Show full size image on click

I have a text + image side by side, and I want a function where the user can click on the image to make it bigger. I'm new to HTML/CSS so I was wondering how I can approach this. Thanks! (demo -> https://jsfiddle.net/DTcHh/6634/)
Is there any way to do this with pure HTML/CSS and no javascript?
The ones I found have been telling me to use javascript such as:
<script type="text/javascript">
function showImage(imgName) {
document.getElementById('largeImg').src = imgName;
showLargeImagePanel();
unselectAll();
}
function showLargeImagePanel() {
document.getElementById('largeImgPanel').style.visibility = 'visible';
}
function unselectAll() {
if(document.selection) document.selection.empty();
if(window.getSelection) window.getSelection().removeAllRanges();
}
function hideMe(obj) {
obj.style.visibility = 'hidden';
}
</script>
Is there a simpler way to do this in HTML/CSS?
You could use a CSS pseudo-class to change the styling when, for example, the mouse is over the image:
img:hover {
width: 300px;
height: 300px;
}
Generally, though, to add interactivity to your web pages, you will have to become acquainted with JavaScript. I don't know of any way to toggle a state (e.g. "zoomed-in") without the use of JavaScript.
You can think of the HTML as defining the content, the CSS as defining how it looks, and the JavaScript as defining how it behaves.