This is just a question to help me understand CSS rendering better.
Lets say we have a million lines of this.
<div class="first">
<div class="second">
<span class="third">Hello World</span>
</div>
</div>
Which would be the fastest way to change the font of Hello World to red?
.third { color: red; }
div.third { color: red; }
div.second div.third { color: red; }
div.first div.second div.third { color: red; }
Also, what if there was at tag in the middle that had a unique id of "foo". Which one of the CSS methods above would be the fastest.
I know why these methods are used etc, im just trying to grasp better the rendering technique of the browsers and i have no idea how to make a test that times it.
UPDATE:
Nice answer Gumbo.
From the looks of it then it would be quicker in a regular site to do the full definition of a tag. Since it finds the parents and narrows the search for every parent found.
That could be bad in the sense you'd have a pretty large CSS file though.
Two things to remember:
This is going to depend on the CSS parser /rendering engine: i.e. it varies from browser to browser.
CSS is really, really, really fast anyway, even at it's slowest the human watching shouldn't notice
In general the simplest things are the fastest (as Gumbo nicely illustrates), but because we're already in such a fast environment don't think that you should sacrifice clarity and appropriate scoping (low specificity is like making everything public sort of). Just avoid * wherever you can :)
According to the Mozilla Developer Center, the most efficient selector for this case would be simply .third
In fact, they state there, explicitly, "Don't qualify Class Rules with tag names". In general, for greatest efficiency, use the simplest selector that matches. That's why .third beats span.third beats .second span.third, etc.
I can't tell what Gumbo's conclusion is meant to be, but Ólafur appears to be drawing the conclusion from it that using more stuff in the selector makes the CSS parsing more efficient, when, in fact, it's just the opposite (assuming other CSS parsing engines work similarly to Mozilla's.)
You have to understand how the selectors are being processed:
.third: get every element and check for a class name third,
div.third: get every DIV element and check for a class name third,
div.second div.third: get every DIV element, check for a class name second, run through these and find every decendant DIV element and check for a class name third,
div.first div.second div.third: get every DIV element, check for a class name first, run through these and find every decendant DIV element, check for a class name second, run through these and finally check for a class name third.
Edit I have to admit, that the procedure above would be the naive approach and is not generally efficient. In fact, there are implementations that go from bottom to top instead from top to bottom:
div.first div.second div.third: get every DIV element, check for a class name third, get the first DIV ancestor that has a class name second, get the first DIV ancestor that has a class name first.
I would say this depends on the browser. Nothing beats an experiment, in this case a simple JavaScript would probably do.
Update: I meant to do something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CSS Speed Test</title>
<style type="text/css">
.first { color: red; }
</style>
<script type="text/javascript">
window.onload = function()
{
var container = document.getElementById("container");
var totalTime = 0;
var passes = 100;
for (var p=1; p<=passes; p++)
{
var startTime = new Date();
for (var i=0; i<1000; i++)
{
var outerDiv = document.createElement("div");
var innerDiv = document.createElement("div");
var span = document.createElement("span");
outerDiv.className = "first";
innerDiv.className = "second";
span.appendChild(document.createTextNode("Hello, world!"));
outerDiv.appendChild(innerDiv);
innerDiv.appendChild(span);
container.appendChild(outerDiv);
}
var endTime = new Date();
totalTime += (endTime - startTime);
}
alert("Average time: " + totalTime/passes);
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
…but the time differences caused by different selectors appear to be too small to measure, just as annakata said.
Related
I am generating a PDF using nodejs with pdf-creator-node and I got success.
My requirement is I need to generate a PDF with Height X Width = 926px X 1296px.
I don' know what css I should write to generate this dimension pdf.
right now if I set div or body height and widht with above mentioned dimension I am getting 3 pages
this is what I tried
#page {
width: 1296px;
height: 926px;
}
<div
class="parent-div"
style="
width: 1296px;
height: 926px;
background-color: #faf0e6;
border: 1px solid red;
"
></div>
jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:
Go to https://github.com/MrRio/jsPDF and download the latest
Version.
Include the following Scripts in your project:
jspdf.js
jspdf.plugin.from_html.js
jspdf.plugin.split_text_to_size.js
jspdf.plugin.standard_fonts_metrics.js
If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:
<!DOCTYPE html>
<html>
<body>
<p id="ignorePDF">don't print this to pdf</p>
<div>
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
Then you use the following JavaScript code to open the created PDF in a PopUp:
var doc = new jsPDF();
var elementHandler = {
#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
source,
15,
15,
{
'width': 180,'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
**For me this created a nice and tidy PDF that only included the line 'print this to pdf'.
Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states:**
Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.
Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:
var elementHandler = {
#ignoreElement': function (element, renderer) {
return true;
},
#anotherIdToBeIgnored': function (element, renderer) {
return true;
}
};
From the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit too unrestrictive for the most use cases though:
We support special element handlers. Register them with a jQuery-style ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) There is no support for any other type of selectors (class, of the compound) at this time.
One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3, etc., which was enough for my purposes. Additionally, it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:
<body>
<ul>
<!-- This is printed as the element contains a textnode -->
<li>Print me!</li>
</ul>
<div>
<!-- This is not printed because jsPDF doesn't deal with the value attribute -->
<input type="textarea" value="Please print me, too!">
</div>
</body>
I would like to reproduce this, just with CSS:
http://jsfiddle.net/g32Xm/
$(function(){
var text = $('h2').text();
var atext = text.split("");
var newText = '';
for(var i=0; i< atext.length; i++){
newText += '<span>'+ atext[i]+'</span>';
}
$('h2').html(newText);
});
CSS
h2 span:hover{
position:relative;
bottom:3px;
}
Is there any workaround that doesn't envolve Javascript? and (i forgot to mention) without putting the spans in the html
Thanks in advance
CSS is generally applied to selectors, not individual letters in a text node. With modern CSS, you can use the :first-letter pseudoelement, but as far as I know, this is about as far as you can go with styling individual characters. The only way is wrapping each character in a separate element (a span, probably) and working with that.
So, to cut the long answer short: as of now, no, there's no way to do that with just CSS.
You can eventually wrap every single character in a span manually and avoid using javascript that way:
HTML
<h2>
<span>M</span><span>a</span><span>n</span><span>d</span><span>a</span><span>r</span><span>i</span><span>n</span><span>a</span>
<span>L</span><span>i</span><span>m</span><span>ó</span><span>n</span>
</h2>
CSS
h2 > span:hover{
position:relative;
bottom:3px;
}
JSFiddle example
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a CSS parent selector?
Is there a css selector I can use only if a child element exists?
Consider:
<div> <ul> <li></li> </ul> </div>
I would like to apply display:none to div only if it doesn't have at least one child <li> element.
Any selector I can use do this?
Sort of, with :empty but it's limited.
Example: http://jsfiddle.net/Ky4dA/3/
Even text nodes will cause the parent to not be deemed empty, so a UL inside the DIV would keep the DIV from being matched.
<h1>Original</h1>
<div><ul><li>An item</li></ul></div>
<h1>No Children - Match</h1>
<div></div>
<h1>Has a Child - No Match</h1>
<div><ul></ul></div>
<h1>Has Text - No Match</h1>
<div>text</div>
DIV {
background-color: red;
height: 20px;
}
DIV:empty {
background-color: green;
}
Reference: http://www.w3.org/TR/selectors/#empty-pseudo
If you go the script route:
// pure JS solution
var divs = document.getElementsByTagName("div");
for( var i = 0; i < divs.length; i++ ){
if( divs[i].childNodes.length == 0 ){ // or whatever condition makes sense
divs[i].style.display = "none";
}
}
Of course, jQuery makes a task like this easier, but this one task isn't sufficient justification to include a whole libary.
Nope, unfortunately that's not possible with CSS selectors.
CSS does not (yet) have any parent rules unfortunately, the only way around it if you must apply it only parents that contain a specific child is with the Javascript, or more easily with a library of javascript called jQuery.
Javascript can be written in a similair way to CSS in someways, for your example we would do something like this at the bottom of our HTML page:
<script type="text/javascript">
$('div:has(ul li)').css("color","red");
</script>
(For this you would need to include the jQuery library in your document, simply by putting the following in your <head></head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
If you use jquery, you can try out this function
jQuery.fn.not_exists = function(){
return this.length <= 0;
}
if ($("div#ID > li").not_exists()) {
// Do something
}
There is another option
$('div ul').each(function(x,r) {
if ($(r).find('li').length < 1){
$(r).css('display','block'); // set display none
}
})
The intent is to target all the other elements of the same type & same level whenever one is hovered. Tried
a:hover ~ a
Only to notice that this doesn't target the elements before the hovered one... Is there a solution with css? Or should I just somehow js my way out of this
This is a variation on the parent or < selector question (of which there are many). I know it's not quite the same, but I'm sure you can imagine how a sibling selector would be derived from a parent selector.
Jonathan Snook has an excellent blog post on why this doesn't exist, and I don't think I can do any better, so I'll leave you to read that if it interests you. Basically, it's a technically difficult job because of the way elements are selected, and it would lead to a whole world of mess in terms of code structure.
So the short answer is, this doesn't exist and you'll need to resort to JS to fix it, I'm afraid.
Edit: Just a couple of examples of fixes. Using jQuery:
$(selector).siblings().css({...});
or if you want to include the element:
$(selector).parent().children().css({...});
Or in vanilla JS:
var element = document.querySelectorAll(selector); // or getElementById or whatever
var siblings = element.parentNode.childNodes;
for (var i = 0; i < siblings.length; i++) {
if (siblings[i] !== element) { // optional
siblings[i].style.color = 'red';
}
}
You can do this by using jQuery to toggle the hover states instead of CSS:
HTML:
<div>
Link 1
Link 2
Link 3
</div>
CSS:
div a {color: #000;}
div a.hover {color: #00f;}
jQuery:
$("div a").hover(
function(){
$("div a").addClass("hover");
},
function(){
$("div a").removeClass("hover");
}
);
Fiddle
I need an if/else statement for my CSS which can count list items. Would this be possible?
Basically I want to say, if there are less than 10 list items, the UL container should be 200px wide, and it there are more than 10 list items, it should be 400px wide. Something like that.
Can it be done?
I would appreciate a working demo on jsFiddle, both so I can see working code, and for anyone who looks here in the future so they can see a working example and how to do it :)
CSS only does styles, but not dynamically (unless with assistance of JS). you can use the following JS snippet for the task. just to make sure, load this at the very last, just before the </body>
<script type="text/javascript">
(function resize() {
//get all lists with selected name
var lists = document.getElementsByClassName('myList');
//loop through all gathered lists
for (i = 0; i < lists.length; i++) {
//shorthand elements for easy use
var list = lists[i];
var items = list.getElementsByTagName('li');
//append class names
list.className = (items.length < 10) ? 'myList less' : 'myList more';
}
}())
</script>
.less{
width:200px;
}
.more{
width:400px;
}
CSS has no if else statements. You can do this easily with jQuery. Another option would be to use LESS or SCSS.
Short answer: no. CSS offers no conditional support.
Long answer: you need to use javascript or a server side language to either add a class when there are more than 10 items (or elements) in the list, or in the case of javascript, directly manipulate the style after it's loaded.
That doesn't sound possible for CSS. There are no logical if/else statements in the CSS spec. Your next best bet would probably be javascript. You could achieve this with jQuery with the following code:
if($('ul#target-list li').length < 10) {
$('ul#target-list').css('width', 200);
}
else {
$('ul#target-list').css('width', 400);
}
Pure CSS3 Solution
If you only want to support CSS3, then this does what you need:
li {
width: 200px;
}
li:nth-last-child(n+11),
li:nth-last-child(n+11) ~ li {
width: 400px;
}
But you will need to make the ul either display: inline-block or float it so that the width is controlled by the li elements themselves. This may require you to wrap the ul (display: inline-block) in a div so that it still is a block element in the flow of the page if you need it so.