In HTML, I am adding rows dynamically in a table
I need to give different colors for alternative rows using CSS
How can I acheive this?
To achieve this effect (known as zebra striping) in all browsers using just CSS you'll need to add a class to each row (e.g. odd and even) and give them different colours.
If you want to achieve this with just CSS and are not concerned with supporting older browsers (IE6-8) you should use the CSS3 nth-child pseudo element. This can achieve the required effect without the extra class mark-up, e.g.
tr:nth-child(odd) {
background-color: #FF0;
}
tr:nth-child(even) {
background-color: #F0F;
}
However if you want full browser support and don't mind using javascript there are a number of scripts available, both jQuery plugins and plain old javascript. Maybe try this for starters?
http://docs.jquery.com/Tutorials:Zebra_Striping_Made_Easy
Just create 2 css classes, and assign them to the tags alternately.
Try this using JQuery:
$('tr:even').css('background-color', 'grey');
See it in action here
What are you using to create the table, if it is rails you can use?:
= cycle('odd', 'even')
or you can do it in PHP like this:
$i = 0;
=($i++%2==1) ? 'odd' : 'even'
You can also try without CSS, its simple.
Code:
**var rowCount = document.getElementById("tableID").rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.style.backgroundColor = "yellow";
cell1.innerHTML = "hey";
var cell2 = row.insertCell(1);
cell2.style.backgroundColor = "green";
cell2.innerHTML = "hello";**
Here its creating dynamically row for the table and filling different color to coloumns.
hope this help..!!
Thanks
just create the css classes for rows(odd and even) but dont forget that the font color for text should be readeable regarding the background color
.row_odd{
background: #ffffff;
color: #000;
}
.row_even{
background: #faf8f5;
color: #000;
}
Then in the xhtml you have to set the class for each row. For example, using php while you are iterating on rows you can set the value of the variable $class.
<tr class="<?=$class?>" onmouseover="">
<td class="center col_check">...</td>
<td class="links">...</td>
<td class="center">...</td>
</tr>
In addition, you can make other css classes for each column depends of what you want!!
Related
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;
Havin a table with kind of
<tr bgcolor="#aacbdd">
And I use reset.css which says
...td { background: transparent; ....
And this rule removes all backgrounds set in bgcolor attribute.
But I can't just refuse using reset.css
And I can't change HTML (there are tons of plain HTML in the site like this)
Goal is to save these bgcolor backgrounds.
I tried
.ololo tr
{
background: inherit;
}
But no use. How do I?
If you only have a few colors, you can use an attribute selector:
[bgcolor="#aacbdd"] {
background: #aacbdd;
}
[bgcolor="#c73cab"] {
background: #c73cab;
}
Here's the fiddle: http://jsfiddle.net/JN3wW/
If you have many many different colors, this can get unwieldy. I'd advise you to rely on JavaScript for that. Here's an example using jQuery:
$('tr[bgcolor]').css('background-color', function () {
return $.attr(this, 'bgcolor');
});
Here's the fiddle: http://jsfiddle.net/JN3wW/4/
You're using a CSS/Stylesheet reset, and in stylesheets, the latest definition will be used.
So try setting the style property of the tr rather than the element attribute.
<tr style="background-color:#aacbdd;">
I'd like to tell the browser to assign certain CSS classes to elements matching a particular selector. Can I do it with pure CSS and if yes, how?
Example: I want all the h5 elements inside a div with id sidebar to have the class ui-corners-all
No, that isn't possible with pure CSS.
Only with JavaScript:
// jQuery
$("h5").addClass("ui-corners-all");
// Pure JavaScript
var elements = document.getElementsByTagName("h5");
for (var i=0; i<elements.length; i++)
{
var el = elements[i];
el.setAttribute( "class", el.getAttribute("class") + " ui-corners-all" );
}
There is no way to assign this value to those elements in pure CSS.
You would need to do:
#sidebar h5
{
}
Then copy all styles from ui-corners-all class into this.
Or alternatively, change your ui-corners-all CSS to:
.ui-corners-all, #sidebar h5
{
}
No, you can't. You can however use Javascript (jQuery recommended) to achieve this effect.