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;
}
Related
In my app, I have movies' details that can be opened, and I want the buttons of the detail to match the movie.
For instance, with the movie "Back to the Future", I have in my data colors = ["#000000","#123123"].
If I do <div [ngStyle]="{'background-color': movie?.colors[0]}"> the div will be of the color I wanted.
My question is, in Ionic, how can I change variables.scss to have these colors (updated when we open a new movie) ?
Because we can't modify tabs with custom css, so I have to add it to variables.scss...
if you want to update any css color or value like font-size like the sass variable at run time use css variables in this way you can update any css property value at run time if it base on css variable like the color in my example but it 's can be any css value
consider this example
style.css
:root {
--color : red;
}
* {
color:var(--color)
}
AppComponent
colorList = ['green', 'blue'];
updateColor(color) {
document.documentElement.style.setProperty(`--color`, color);
}
Template
<button *ngFor="let c of colorList" (click)="updateColor(c)">{{c}}</button>
stackblitz demo 🚀🚀
sass variable are going to compile at build time to there values so they are not reusable at run time
For most use cases, it is convenient to programmatically change the CSS value of an element by mapping it with a variable. We want the CSS value to change every time we update the variable, not only through this.ngZone.run().
<div class="progress" [style.height]=currentLevelPercentage>
This example has shown how we can map the height CSS property of the div element (class progress) to the variable currentLevelPercentage and change its value dynamically. currentLevelPercentage is the variable that must be compulsorily present in the TypeScript file.
For those here to know how to change color of each tab background in super-tabs (ionic) here's my 4 tabs code (I can now change height and width with code too ^^).
in tabs-page.scss :
:root {
--color1: white;
--color2: white;
--color3: white;
--color4: white;
}
super-tab-button:nth-of-type(1) {
background-color: var(--color1)
}
super-tab-button:nth-of-type(2) {
background-color: var(--color2)
}
super-tab-button:nth-of-type(3) {
background-color: var(--color3)
}
super-tab-button:nth-of-type(4) {
background-color: var(--color4)
}
in tabs-page.html : do nothing particular
in tabs-page.ts :
constructor(public navCtrl: NavController, public navParams: NavParams) {
document.documentElement.style.setProperty('--color1', this.movie.colors[0]);
document.documentElement.style.setProperty('--color2', this.movie.colors[1]);
document.documentElement.style.setProperty('--color3', this.movie.colors[2]);
document.documentElement.style.setProperty('--color4', this.movie.colors[3]);
}
Thank you #malbarmawi !
Just an idea about changing style dynamically. here is what i am using
<span [style.width]=foo></span>
Change the value of ‘foo’ in your .ts file
https://angular.io/docs/ts/latest/guide/template-syntax.html#!#style-binding
Simply try this
[ngStyle]="{'background-color': item.color}"
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
I want to color text based on its value, using css.
ie. if value is less than 20 --> red ,
if value is between 20 - 60 --> orange ,
if value is greater than 60 to 100--> green.
I don't want to add any class in the template depending on the value.
I found this Link: How do I change the background color with JavaScript? but it doesn't suffice as I have too many values to apply color to.
Also I want it to be more maintainable when adding new values in future.
It is not possible only with CSS.
You have to use JavaScript/jQuery to dynamically add the color, based on an object color match, and test if the value in the data-color HTML attribute is between the range for each element.
The JS code dynamically check if the element attribute is in a color range and apply the matched color.
If you will have to add some color and range in the future, simply add new values in the colorMatch hash, and update your CSS color class list.
##CSS
.red {color:red}
###HTML
<p data-color="19">Lorem 19</p>
###JS
var colorMatch = {
'0-19' : 'red',
'20-59' : 'orange',
'60-100' : 'green'
};
Here is the working fiddle
If you do not consider it cheating to not use the actual innerHTML as a condition, but rather construct it from a CSS variable using content you could do something like this (just as an effort to not use JS in this case):
<num style="--num:1"></num>
<num style="--num:99"></num>
<num style="--num:165"></num>
num {
--breakpoint: 100;
--g: calc((clamp(0, var(--num), var(--breakpoint)) - calc(var(--breakpoint) - 1)) * 255);
color: rgb(0, var(--g), 0);
}
num:after {
counter-reset: variable var(--num);
content: counter(variable);
}
In this scenario I am coloring any of the numbers green if they are above 100, but more rules can be added using the same method to serve your use-case.
With that said, I think there is probably no scenario where this would ever be useful, other than just technical trivia, as it is more readable to simply change the class of the element dynamically using plain JS. Still kinda fun way to use counter-reset and counter though.
Here is the same example on jsfiddle: https://jsfiddle.net/msz1aouc/24/
A simple approach could be
HTML
<div class="content">
<p>high</p>
</div>
<div class="content">
<p>low</p>
</div>
<div class="content">
<p>medium</p>
</div>
<div class="content">
<p>critical</p>
</div>
<div class="content">
<p>high</p>
</div>
Jquery
var content = $(".content p").text();
if (content == "high") {
$(this).css("color", "#ffffff");
}
if (content == "low") {
$(this).css("color", "#ccc");
}
if (content == "critical") {
$(this).css("color", "#000");
}
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;
I'm creating a tumblr them and I have to write an external CSS file but I am having trouble editing the css style of the post elements.
This its structure:
<li class="post quote">
{other code}
</li>
The problem is that the class name has a space in it.
How would I create a CSS class to access this? And yes, I know I can just put a style attribute in the element tag but I was kind of hoping for another option.
The problem is that the class name has a space in it.
This is not possible in CSS. What you are doing is giving the element two classes.
You can address them such:
.post.quote { .... }
but in your case, it's probably better to use a valid separator like
post_quote
This element actually has two classes - it is marked with both the post class and the quote class. So, you can use the following selectors to access it:
// css
.post { ... } // elements with the post class
.quote { ... } // elements with the quote class
// jQuery
var postLis = $('.post');
var quoteLis = $('.quote');
You can also stack selectors to return all elements which meet all conditions in the selector, by including the different selectors together:
// css
.post.quote { ... } // elements with both the post and quote classes
// jQuery
var postAndQuoteLis = $('.post.quote');
This might work:
$('li').each(function() {
if($(this).attr('class').indexOf(" ")>-1) {
$(this).css('border','1px solid #ff0000')
}
}