I'm doing a little experiment, trying to alternate background colours for nested divs.
This is what I intend to achieve (without the inline styles):
<div style="background: #fff;">
<div style="background: #000;">
<div style="background: #fff;">
<div style="background: #000;">
and so on...
</div>
</div>
</div>
</div>
I feel like I must be missing something obvious! I tried div:nth-of-type(2n) but this appears to only apply on one level.
This is for an experiment where the divs are generated, so the solution needs to be endless (not something along the lines of div div div div = white). I know it's quite easy with JavaScript, just looking for a pure CSS solution.
As Mr Lister pointed out, nth-of-type works on one level (that of the parent of the selected div).
As far as i know and after looking through the W3C CSS3 Selectors there doesn't appear to be any css selectors for traversing through nesting (except the > selector, which only looks at the direct child of parent).
I would love te be proven wrong though as that could be very usefull.
So the only (css) solution would be the one you already stated: div > div > div {background: white; }
Can't you just generate this along with the generation of the div's?
As stated by others, this is not possible in pure CSS. However using js it is quite possible and fairly easy too.
For ease I implemented this in jQuery but you could do with pure JS.
http://jsfiddle.net/sg3s/Suf3p/
I basically made a small jQuery plugin that colors the selector you apply it on with the primary color, and uses the subselect to get a matching child to color with the secondary color and so on until no children matching the subselect are left.
jQuery(function($) {
$.fn.alternateNestedBgColor = function(subselect, colors) {
// While not a great optimization, length of the colors array always stays the same
var l = colors.length;
// Itterate over all element in possible array
// jQuery best practice to handle initializing multiple elements at once
return this.each(function() {
var $sub = $(this), i = 0;
// Executes code, at least once
do {
// Set bg color for current $sub element
$sub.css('backgroundColor', colors[i++ % l]);
// Set $sub to direct children matching given selector
$sub = $sub.children(subselect);
// Will repeat the do section if the condition returns true
} while ($sub.length > 0);
});
};
// target first div in the body
// first argument = child selector
// second argument = array list of colors
$('body>div').alternateNestedBgColor('div', ['red', 'green', 'blue', 'purple', 'grey']);
});
Update As requested an update detailing how apply and modulo were used.
It's been almost 2 year since I recently posted this. And while working, the solution I made back then was a bit verbose and confusing, as for instance, I never needed apply. I got a little bit more comfortable with scopes, so I revised the function to be much simpler.
The only situation where apply is useful is when you need to pass a value to the this variable inside the function scope. Unless working with classes there aren't a whole lot of situations you should have a need for apply or call. If you want to read up on it I would like to refer you to this answer which explains it in context of classes. The MDN link is a good resource as well (for this and other javascript constructs/concepts).
As for modulo, this is basic math and this question explains the operation quite well. In short it will give you the full integer remainder after dividing a number by another. So 33 % 8 = 1 which you could write as 33-parseInt(33/8)*8 in js though that would be grossly inefficient. The result of the operation will always be 0 (when the number perfectly divides) to the 2nd argument minus 1 (so 7 in my example).
0 % 3 = 0 // technically doesn't exist (as you can't divide 0 with anything) but 0 for practicality in all programming languages afaik(?)
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0 etc...
It's one of those operations which is inherently simple for your CPU, in fact without it being able to do this we wouldn't have computers.
In the javascript revision I've written the selection of the color from the given array as colors[i++ % l].
In writing this would be give me the remainder of i / l and use that integer as an index for the colors array which returns a color for use.
The ++ will add 1 only after returning the value of i for use in the modulo, this behaviour would be reversed if I had written ++i, but that wouldn't work for our purpose here.
For reference here is the MDN article on do...while.
I hope that cleared some things up! :)
Related
I know the basics of CSS but haven't found an answer to this.
Previously, I had :
li[data-sizex="1"] .widget.widget-jenkins-view-build-status
to apply a certain style to all the widgets of this kind under li tags with sizex set to 1.
But now I want to apply it to those with sizey set to 1 too, so I wrote :
li[data-sizex="1"] .widget.widget-jenkins-view-build-status, li[data-sizey="1"] .widget.widget-jenkins-view-build-status
It works, but here's my question : is there a way to regroup/shorten/factorize this, to avoid repetition of the widget, without adding new elements such as classes ? A pure factorization like in math : A with C or B with C <==> (A or B) with C .
Thank you.
The main question is:
Should I define unit in sass variables?
I am a Sass beginner, I've already searched about best practices (and I am trying to apply them) but I could found nothing about this question.
Let me explain with examples. I am working on a website which some sections will be overridden by the customer. So, I have some sass variables that I expect my custumer override them. Some of these variables are width, for example. I've started defining all with unit included, like:
$my-app-main-container-width: 150px !default;
However, in some cases, I need to use variables to do math operations:
$density: 5;
#for $i from 1 through 10 {
.app-item-#{$i} {
padding: #{$density}px #{$density}px #{$density}px #{$i * $density + $density}px;
}
}
So I realized that in some cases I've declared the variable with px and in other cases, just the number. In my research, all samples are including the unit in variable value, but sounds weird and inconsistent when you need to calc. But, like I've said, I am a sass beginner so I will enjoy other opinions.
For now, I am omitting the unit in all my variables and defining the unit when I use the variable.
Suppose, I am creating an image gallery; at a certain device width, there will be three images, hence, I need to work out one third:
{width:calc(100% / 3)}
However, the issue is that I need to take away '2px' (two pixels) - I added a margin of 1px, hence this needs to be accounted for by taking this away from the width, hence I need to do:
{width:calc(calc(100% / 3) - 2px)}
But, this does not work: is there a way I can do this?
[I need to work out a third, then take two pixels away from this -- it is messy because a third is difficult to format as a percentage.]
For the sake of completeness, I will add an answer here (The solution has already been posted in the comments underneath the asker's question).
You don't need to use two calc() statements. It's sufficient for you to combine the calculations within one calc() statement. In this case, as Andrea Ghidini mentioned in a comment (refer to this link), the division will take precedence over the subtraction (basic math rules apply!).
So your solution would be:
width:calc(100% / 3 - 2px)
Also, make sure that additions and subtractions are surrounded by whitespaces, otherwise it will not work!
So I've now read enough about various funky nth-child and nth-of-type patterns to have the seventh son of the seventh son fly a space-ship backwards to Pluto and back. But I still haven't come across a way to simply provide a list of specific children in a concise way. It'd work like so:
td:nth-child(1,3,7,10) { text-align: center; ... }
The above syntax would obviously be mighty convenient for example when styling table cells. That something like this would exist, seems like a no-brainer to me. Of course I can always use:
td:nth-child(1), td:nth-child(3), td:nth-child(7), td:nth-child(10) { ... }
But that's just so much redundant repetition and clutter in my CSS. Particularly when I need to also have a class name specified before the td. Then it becomes as bloated as this, for example:
.study_references td:nth-child(1), .study_references td:nth-child(3), .study_references td:nth-child(7), .study_references td:nth-child(10) { ... }
I'd really like to have my CSS look a bit more elegant, concise, and readable. Is there really no way to provide a specific list of nth-s to the selector in one shot? (Not looking for a preprocessor fix.)
Unfortunately there isn't. Neither Selectors 4 nor CSS Syntax 3 have extended the An+B notation to allow a list of such expressions as in your 1,3,7,10 example either, though I wonder if it may be worth suggesting as it seems pretty doable. In fact, I just went ahead and suggested this (I couldn't find any earlier proposals using either the mailing list search, or Google).
The closest to a solution that Selectors 4 offers is via the :matches() pseudo, which makes it so that the only bit you have to repeat is :nth-child(...):
.study_references td:matches(
:nth-child(1), :nth-child(3), :nth-child(7), :nth-child(10)
) { ... }
But this is still far from ideal, and is not yet implemented anyway.
If you can suss out at least part of a pattern from most of the numeric indices you're looking for, you could modify this pattern as necessary using :not() and/or additional :nth-child()/:nth-last-child() and still pick up the right elements. See this answer of mine where I refactor [9, 11, n+12] into [n+9 except 10]. However this is likely more trouble than it's worth, and the resulting selector will almost always be far from elegant unless you get really lucky as I did above.
When CSS lacks a feature, Sass can help. You can try a formula like this one in Sass. It's not the most elegant solution, but perhaps you can improve on it.
$children: 1,3,7,10;
#each $child in $children {
td:nth-child(#{$child}) {
...
}
}
Please read my question before you report it as a duplicate. In the literature, to find the minimum height of a tree, the common approach is as follow:
int minDepth(TreeNode root) {
if (root == null) { return 0;}
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
However, I think it does not distinguish between a leaf and a node with only one child and so it returns a wrong value. For example if our tree looks like this:
A is root
B is the left child of A
C is the right child of B
M is the left child of C
This function returns one while the leaf is 3 hop away from the root and so the min height is 4.
Since this recursive version is generally suggested in the literature, I think I am missing something.
Could somebody clear this for me?
Your comments indicate that the texts where you found this actually use the same definitions for the terms I use. If that is indeed the case, then the question is not why the algorithm you have shown is correct – it simply is wrong under those conditions.
Just take the third simplest binary tree, the one consisting of two nodes. It has exactly one leaf, its depth is two and its minimal depth is also two. But the algorithm you quoted returns the value one. So, unless the authors use a different definition for one of the terms (e.g., “minimal height” meaning “shortest path out of the tree”/“shortest path to a null pointer”), the result is simply wrong.