I would like to use conditions in my CSS.
The idea is that I have a variable that I replace when the site is run to generate the right style-sheet.
I want it so that according to this variable the style-sheet changes!
It looks like:
[if {var} eq 2 ]
background-position : 150px 8px;
[else]
background-position : 4px 8px;
Can this be done? How do you do this?
Not in the traditional sense, but you can use classes for this, if you have access to the HTML. Consider this:
<p class="normal">Text</p>
<p class="active">Text</p>
and in your CSS file:
p.normal {
background-position : 150px 8px;
}
p.active {
background-position : 4px 8px;
}
That's the CSS way to do it.
Then there are CSS preprocessors like Sass. You can use conditionals there, which'd look like this:
$type: monster;
p {
#if $type == ocean {
color: blue;
} #else if $type == matador {
color: red;
} #else if $type == monster {
color: green;
} #else {
color: black;
}
}
Disadvantages are, that you're bound to pre-process your stylesheets, and that the condition is evaluated at compile time, not run time.
A newer feature of CSS proper are custom properties (a.k.a. CSS variables). They are evaluated at run time (in browsers supporting them).
With them you could do something along the line:
:root {
--main-bg-color: brown;
}
.one {
background-color: var(--main-bg-color);
}
.two {
background-color: black;
}
Finally, you can preprocess your stylesheet with your favourite server-side language. If you're using PHP, serve a style.css.php file, that looks something like this:
p {
background-position: <?php echo (#$_GET['foo'] == 'bar')? "150" : "4"; ?>px 8px;
}
In this case, you will however have a performance impact, since caching such a stylesheet will be difficult.
I am surprised that nobody has mentioned CSS pseudo-classes, which are also a sort-of conditionals in CSS. You can do some pretty advanced things with this, without a single line of JavaScript.
Some pseudo-classes:
:active - Is the element being clicked?
:checked - Is the radio/checkbox/option checked? (This allows for conditional styling through the use of a checkbox!)
:empty - Is the element empty?
:fullscreen - Is the document in full-screen mode?
:focus - Does the element have keyboard focus?
:focus-within - Does the element, or any of its children, have keyboard focus?
:has([selector]) - Does the element contain a child that matches [selector]? (Sadly, not supported by any of the major browsers.)
:hover - Does the mouse hover over this element?
:in-range/:out-of-range - Is the input value between/outside min and max limits?
:invalid/:valid - Does the form element have invalid/valid contents?
:link - Is this an unvisited link?
:not() - Invert the selector.
:target - Is this element the target of the URL fragment?
:visited - Has the user visited this link before?
Example:
div { color: white; background: red }
input:checked + div { background: green }
<input type=checkbox>Click me!
<div>Red or green?</div>
Update:
I've written a article regarding the below unique method in CSS-Tricks which goes into futher detail
I've devised the below demo using a mix of tricks which allows simulating if/else scenarios for some properties. Any property which is numerical in its essence is easy target for this method, but properties with text values are.
This code has 3 if/else scenarios, for opacity, background color & width. All 3 are governed by two Boolean variables bool and its opposite notBool.
Those two Booleans are the key to this method, and to achieve a Boolean out of a none-boolean dynamic value, requires some math which luckily CSS allows using min & max functions.
Obviously those functions (min/max) are supported in recent browsers' versions which also supports CSS custom properties (variables).
var elm = document.querySelector('div')
setInterval(()=>{
elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
:root{
--color1: lightgreen;
--color2: salmon;
--width: 70; /* starting value, randomly changed by javascript every 1 second */
}
div{
--widthThreshold: 50;
--is-width-above-limit: Min(1, Max(var(--width) - var(--widthThreshold), 0));
--is-width-below-limit: calc(1 - var(--is-width-above-limit));
--opacity-wide: .4; /* if width is ABOVE 50 */
--radius-narrow: 10px; /* if width is BELOW 50 */
--radius-wide: 60px; /* if width is ABOVE 50 */
--height-narrow: 80px; /* if width is ABOVE 50 */
--height-wide: 160px; /* if width is ABOVE 50 */
--radiusToggle: Max(var(--radius-narrow), var(--radius-wide) * var(--is-width-above-limit));
--opacityToggle: calc(calc(1 + var(--opacity-wide)) - var(--is-width-above-limit));
--colorsToggle: var(--color1) calc(100% * var(--is-width-above-limit)),
var(--color2) calc(100% * var(--is-width-above-limit)),
var(--color2) calc(100% * (1 - var(--is-width-above-limit)));
--height: Max(var(--height-wide) * var(--is-width-above-limit), var(--height-narrow));
height: var(--height);
text-align: center;
line-height: var(--height);
width: calc(var(--width) * 1%);
opacity: var(--opacityToggle);
border-radius: var(--radiusToggle);
background: linear-gradient(var(--colorsToggle));
transition: .3s;
}
/* prints some variables */
div::before{
counter-reset: aa var(--width);
content: counter(aa)"%";
}
div::after{
counter-reset: bb var(--is-width-above-limit);
content: " is over 50% ? "counter(bb);
}
<div></div>
Another simple way using clamp:
label{ --width: 150 }
input:checked + div{ --width: 400 }
div{
--isWide: Clamp(0, (var(--width) - 150) * 99999, 1);
width: calc(var(--width) * 1px);
height: 150px;
border-radius: calc(var(--isWide) * 20px); /* if wide - add radius */
background: lightgreen;
}
<label>
<input type='checkbox' hidden>
<div>Click to toggle width</div>
</label>
Best so far:
I have come up with a totally unique method, which is even simpler!
This method is so cool because it is so easy to implement and also to understand. it is based on animation step() function.
Since bool can be easily calculated as either 0 or 1, this value can be used in the step! if only a single step is defined, then the if/else problem is solved.
Using the keyword forwards persist the changes.
var elm = document.querySelector('div')
setInterval(()=>{
elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
:root{
--color1: salmon;
--color2: lightgreen;
}
#keyframes if-over-threshold--container{
to{
--height: 160px;
--radius: 30px;
--color: var(--color2);
opacity: .4; /* consider this as additional, never-before, style */
}
}
#keyframes if-over-threshold--after{
to{
content: "true";
color: green;
}
}
div{
--width: 70; /* must be unitless */
--height: 80px;
--radius: 10px;
--color: var(--color1);
--widthThreshold: 50;
--is-width-over-threshold: Min(1, Max(var(--width) - var(--widthThreshold), 0));
text-align: center;
white-space: nowrap;
transition: .3s;
/* if element is narrower than --widthThreshold */
width: calc(var(--width) * 1%);
height: var(--height);
line-height: var(--height);
border-radius: var(--radius);
background: var(--color);
/* else */
animation: if-over-threshold--container forwards steps(var(--is-width-over-threshold));
}
/* prints some variables */
div::before{
counter-reset: aa var(--width);
content: counter(aa)"% is over 50% width ? ";
}
div::after{
content: 'false';
font-weight: bold;
color: darkred;
/* if element is wider than --widthThreshold */
animation: if-over-threshold--after forwards steps(var(--is-width-over-threshold)) ;
}
<div></div>
I've found a Chrome bug which I have reported that can affect this method in some situations where specific type of calculations is necessary, but there's a way around it.
You can use calc() in combination with var() to sort of mimic conditionals:
:root {
--var-eq-two: 0;
}
.var-eq-two {
--var-eq-two: 1;
}
.block {
background-position: calc(
150px * var(--var-eq-two) +
4px * (1 - var(--var-eq-two))
) 8px;
}
concept
Below is my old answer which is still valid but I have a more opinionated approach today:
One of the reasons why CSS sucks so much is exactly that it doesn't have conditional syntax. CSS is per se completely unusable in the modern web stack. Use SASS for just a little while and you'll know why I say that. SASS has conditional syntax... and a LOT of other advantages over primitive CSS too.
Old answer (still valid):
It cannot be done in CSS in general!
You have the browser conditionals like:
/*[if IE]*/
body {height:100%;}
/*[endif]*/
But nobody keeps you from using Javascript to alter the DOM or assigning classes dynamically or even concatenating styles in your respective programming language.
I sometimes send css classes as strings to the view and echo them into the code like that (php):
<div id="myid" class="<?php echo $this->cssClass; ?>">content</div>
You could create two separate stylesheets and include one of them based on the comparison result
In one of the you can put
background-position : 150px 8px;
In the other one
background-position : 4px 8px;
I think that the only check you can perform in CSS is browser recognition:
Conditional-CSS
CSS is a nicely designed paradigm, and many of it's features are not much used.
If by a condition and variable you mean a mechanism to distribute a change of some value to the whole document, or under a scope of some element, then this is how to do it:
var myVar = 4;
document.body.className = (myVar == 5 ? "active" : "normal");
body.active .menuItem {
background-position : 150px 8px;
background-color: black;
}
body.normal .menuItem {
background-position : 4px 8px;
background-color: green;
}
<body>
<div class="menuItem"></div>
</body>
This way, you distribute the impact of the variable throughout the CSS styles.
This is similar to what #amichai and #SeReGa propose, but more versatile.
Another such trick is to distribute the ID of some active item throughout the document, e.g. again when highlighting a menu: (Freemarker syntax used)
var chosenCategory = 15;
document.body.className = "category" + chosenCategory;
<#list categories as cat >
body.category${cat.id} .menuItem { font-weight: bold; }
</#list>
<body>
<div class="menuItem"></div>
</body>
Sure,this is only practical with a limited set of items, like categories or states, and not unlimited sets like e-shop goods, otherwise the generated CSS would be too big. But it is especially convenient when generating static offline documents.
One more trick to do "conditions" with CSS in combination with the generating platform is this:
.myList {
/* Default list formatting */
}
.myList.count0 {
/* Hide the list when there is no item. */
display: none;
}
.myList.count1 {
/* Special treatment if there is just 1 item */
color: gray;
}
<ul class="myList count${items.size()}">
<!-- Iterate list's items here -->
<li>Something...</div>
</ul>
You can use not instead of if like
.Container *:not(a)
{
color: #fff;
}
Set the server up to parse css files as PHP and then define the variable variable with a simple PHP statement.
Of course this assumes you are using PHP...
This is a little extra info to the Boldewyn answer above.
Add some php code to do the if/else
if($x==1){
print "<p class=\"normal\">Text</p>\n";
} else {
print "<p class=\"active\">Text</p>\n";
}
CSS has a feature: Conditional Rules. This feature of CSS is applied based on a specific condition. Conditional Rules are:
#supports
#media
#document
Syntax:
#supports ("condition") {
/* your css style */
}
Example code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Supports Rule</title>
<style>
#supports (display: block) {
section h1 {
background-color: pink;
color: white;
}
section h2 {
background-color: pink;
color: black;
}
}
</style>
</head>
<body>
<section>
<h1>Stackoverflow</h1>
<h2>Stackoverflow</h2>
</section>
</body>
</html>
As far as i know, there is no if/then/else in css. Alternatively, you can use javascript function to alter the background-position property of an element.
Yet another option (based on whether you want that if statement to be dynamically evaluated or not) is to use the C preprocessor, as described here.
You can use javascript for this purpose, this way:
first you set the CSS for the 'normal' class and for the 'active' class
then you give to your element the id 'MyElement'
and now you make your condition in JavaScript, something like the example below... (you can run it, change the value of myVar to 5 and you will see how it works)
var myVar = 4;
if(myVar == 5){
document.getElementById("MyElement").className = "active";
}
else{
document.getElementById("MyElement").className = "normal";
}
.active{
background-position : 150px 8px;
background-color: black;
}
.normal{
background-position : 4px 8px;
background-color: green;
}
div{
width: 100px;
height: 100px;
}
<div id="MyElement">
</div>
You can add container div for all your condition scope.
Add the condition value as a class to the container div. (you can set it by server side programming - php/asp...)
<!--container div-->
<div class="true-value">
<!-- your content -->
<p>my content</p>
<p>my content</p>
<p>my content</p>
</div>
Now you can use the container class as a global variable for all elements in the div using a nested selector, without adding the class to each element.
.true-value p{
background-color:green;
}
.false-value p{
background-color:red;
}
Besides the answers above, soon another way to directly use if/else -like conditions, and even more closely aligned with other scripting languages, would be via #when / #else conditionals. These conditionals would be implemented to exercise easily recognizable logic chain, for example:
#when supports(display: flex) {
.container {
display: flex
}
} #else media and (min-width: 768px) {
.container {
min-width: 768px
}
} #else {
.container {
width: 100%
}
}
As of February 2022 there is no browser support. Please see this W3C module for more info.
(Yes, old thread. But it turned up on top of a Google-search so others might be interested as well)
I guess the if/else-logic could be done with javascript, which in turn can dynamically load/unload stylesheets. I haven't tested this across browsers etc. but it should work. This will get you started:
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
If you're open to using jquery, you can set conditional statements using javascript within the html:
$('.class').css("color",((Variable > 0) ? "#009933":"#000"));
This will change the text color of .class to green if the value of Variable is greater than 0.
Related
Presentation
I'm trying to build a web site available in multiple cultures, with different reading direction.
To do so, I simply add the dir="rtl" attribute on my root HTML element.
My issue is that I have some CSS rules that are specific to one direction or the other (margins or paddings, most of the times).
Unsuccessful try with attribute selector
I though that I could simply use the attribute selector but the dir attribute is only set on the root element, so this wouldn't work :
selector {
&[dir="ltr"] {
// LTR specific
}
&[dir="rtl"] {
// RTL specific
}
}
For instance, on this demo, the title should have a margin of 5px on the right if the application is in rtl or on the left if it's in standard ltr.
Other idea
I've noticed that the direction is rightfully set at rtl, is there a way to use that rule within a CSS or Sass selector ?
Edit and precisions
It seems that I've forgotten an important point. I'm building the web site using Vue.js, the dir attribute is bind in the main component (App) and the RTL/LTR specific CSS rules can be in the same component or in other self-contained component.
Following your css code you could do this with SASS at-root directive DEMO. So this:
#app {
width: 300px;
height: 100px;
border: 1px solid red;
h1 {
#at-root {
[dir="rtl"]#{&} {color: green}
}
#at-root {
[dir="ltr"]#{&} {color: red}
}
}
}
It will compile to this css.
#app {
width: 300px;
height: 100px;
border: 1px solid red;
}
[dir="rtl"]#app h1 {
color: green;
}
[dir="ltr"]#app h1 {
color: red;
}
You could style everything LTR, and only adjust some elements styling for RTL. Might this work for you?
[dir="rtl"] {
&selector {
// RTL specific
}
&selectorN {
// RTL specific
}
}
Use below scss to get expected output
#app {
width: 300px;
height: 300px;
background: red;
&[dir="ltr"] h1{
margin-left: 10px;
}
&[dir="rtl"] h1 {
margin-right: 10px;
}
}
Probably you are going a little in the wrong direction.
Most of the time, you can achieve this automatically, no need for specific selectors.
Margin, for instance:
Just set it both for left and right margin. The browser will choose the correct one for you
#app {
width: 300px;
background: tomato;
margin: 10px;
}
h1 {
margin-left: 15px;
margin-right: 5px;
}
<div id="app" dir="ltr">
<h1>
margin left 15
</h1>
</div><div id="app" dir="rtl">
<h1>
margin right 5
</h1>
</div>
I recently started using BEM methodology and I'm confused about class inheritance, or rather - when we talk about BEM - some use cases of modifiers.
Let's look at this example, I have a simple element with few children
.b-content { width: 100%; }
.b-content__image { display: block; }
.b-content__date { font-size: 14px; }
.b-content__title { font-size: 30px; }
.b-content__text { font-size: 16px; }
Now I want to reuse my .b-content block with slightly different styles, so I use modifier .m-compact and now I'm not sure what approach is the right one (in BEM).
Whether I should append modifier class to all elements (which I find more valid according to documentation):
.b-content.m-compact { width: 50%; }
.b-content__image.m-compact { display: none; }
.b-content__date.m-compact { font-size: 12px; }
.b-content__title.m-compact { font-size: 24px; }
.b-content__text.m-compact { font-size: 14px; }
or should I append modifier only to the parent element:
.b-content.m-compact { width: 50%; }
.b-content.m-compact .b-content__image { display: none; }
.b-content.m-compact .b-content__date { font-size: 12px; }
.b-content.m-compact .b-content__title { font-size: 24px; }
.b-content.m-compact .b-content__text { font-size: 14px; }
I find this second method more logical, you know, since I'm writing cascading styles and in real world if I want to write e-mail to 10 people, I would write one and just add more recipients, but on the other hand I realize BEM is practically non-cascading approach.
So what should I use and why?
As you point out in the last lines of your question, when doing BEM you should avoid cascading so, as a corollary to this, you don't have to repeat the modifier where it isn't needed.
For your Modifier I'd write something like this:
.b-content--m-compact {
width: 50%;
}
In your example the Block and the Modifier set only the width, so this is a limited use case. In general it comes handy to use some kind of CSS preprocess to ease the code writing, e.g. in SASS:
.my-block
width: 100%
color: red
&--modifier
#extend .my-block
border: 1px solid red
which will results in:
.my-block, .my-block--modifier {
width: 100%;
color: red;
}
.my-block--modifier {
border: 1px solid red;
}
Modifier in BEM looks like this: .block_modName_modValue
You can add additional class - but it's not BEM. And also modifiers have a name and value.
Block in BEM set namespace
So you set default styles for blocks and all unique(that can be changed) place in css with modifiers. This way your styles don't messed up.
To do this you need:
Place common styles in block styles(.portfolio)
Place unique style(with modifiers) like this.(portfolio_theme_list)
In css you don't need to separate this(preprocessor will be needed).
.portfolio {
/* common styles */
&_theme_list {
/* modifiers style */
}
}
In BEM project-stub(template engine) it would look like this:
If you add modifier to block. Then compile(bemjson) to html.
{
block : 'portfolio',
mods : { theme : 'list' },
}
You will see this code
<div class="portfolio portfolio_theme_list">
</div>
You write elements correctly and understand that they need to be separated(without inheritence).
So now you need just define styles for your block with modifier(portfolio_theme_list).
You have 2 options:
1) If you have 2 different blocks - you need separate common and
unique styles. Unique styles place in styles with modified blocks.
2) If you have only 1 different block & you already have styles on
this blocks. Then you can override and don't separate common
styles(but it can cause pain if you add another modifier/instance)
I want to have some visual notification when something is good, bad or in between
lets say I have a number between 0 and 100, where 100 is green (or some other predefined color) and 0 is red (or another color)
is there a way to get the color that is 67? 34? 98? with only css
so 67 in this case, could either be (67 * green + 33 * red) / 100 or some other function
another alternative would be to make a gradient (but then it wouldn't be a solid color..)
Currently, there is no stable way to do that in CSS, only. CSS calc() property will probably the way to go as the W3C specs include that you can use values from attr() for calculations. As of now, no browser supports the combination of both, but it would look like this
// HTML
<span class="color" data-val="67">67</span>
// CSS
.color {
background-color: rgb(
calc( (100 - attr(data-val)) / 100 * 255 ),
calc( attr(data-val) / 100 * 255),
0
);
}
calc() itself works quite well (with prefixes in Chrome (-webkit-) and Firefox (-moz-), but the numbers used for calculation must be set in CSS (e.g. width: calc(100% - 3em);).
Before attr() is fully supported inside calc(), you probably need to use javascript to achieve that, see example below where the span has a red background and the inner strong element has a green background color. Javascript is used to set the background opacity based on the text value. Press Run code snippet to see the result.
$(document).ready(function() {
$('.color').each(function() {
$(this).children('strong').css('background-color', 'rgba(0,255,0,'+(parseInt($(this).text()) / 100)+')');
});
});
.color {
display: inline-block;
margin: 5px;
text-align: center;
border: 1px solid #000;
background: #c00;
}
strong {
display: inline-block;
padding: 15px;
color: #fff;
text-shadow: 0 0 5px #000;
font-family: Arial;
font-size: 1.2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<span class="color"><strong>100</strong></span>
<span class="color"><strong>67</strong></span>
<span class="color"><strong>33</strong></span>
<span class="color"><strong>25</strong></span>
<span class="color"><strong>0</strong></span>
The only way you can do this with CSS is to write a class for every single possible color. The only way Sass can help is by programatically generating all of your classes:
#for $i from 0 through 100 {
.foo-#{$i} {
background: mix(red, green, $i * 1%);
}
}
This task can be more efficiently solved via JavaScript.
You can but it requires SASS or LESS or another pre-processor that allows CSS variables
SASS
$value: 0;
$green: 255*($value/100);
$red:255*((100-$value)/100);
div {
width:100px;
height:100px;
margin:10px;
background:rgb($red, $green , 0);
}
SassMeister Demo
I have the following HTML:
<div class="float-left inline orderby">
<div class="arrow up" style="margin-bottom: 2px; margin-left: 2px"></div>
<div class="arrow down" style="margin-left: 2px;"></div>
<input type="checkbox" data-ng-model="inverse" style="margin-left: 0px; margin-right: 10px;">
</div>
I'm trying to use the less pre-processor to create my CSS.
How can I use less to create CSS to remove the styles from this example. In particular I am not sure how to handle the difference between the 1st and 2nd DIV
You mean you want to remove the inline styles?
.orderby .arrow, .orderby input {
margin: 0;
&.up {
/* styles for first div */
}
&.down {
/* styles for second div */
}
}
It's a little unclear exactly what your question is. I can read it two ways:
(1) You cannot remove css set with style with LESS
If you actually have a style property on your html elements, then that cannot be directly affected by LESS at all (so it cannot be "removed" by LESS). Additionally, the only way to overcome those styles with LESS is by using the exact same solution you would have available with CSS, the !important attribute (which I despise, but the facts are the facts when it comes to what is available for CSS styling). So this would remove the margins imposed by the style for all direct children in your div (as your example has):
.orderby > * {
margin: 0 !important;
}
But perhaps you want to know how...
(2) You can move the code from the style to the LESS
In which case, it is something like this:
LESS
.orderby {
.arrow {
margin-left: 2px;
&:first-child { /* or could use &.up */
margin-top: 2px;
}
}
input {
margin-left: 0;
margin-right: 10px;
}
}
CSS Output
.orderby {
.arrow {
margin-left: 2px
&:first-child { /* or could use &.up */
margin-top: 2px;
}
}
input {
margin-left: 0;
margin-right: 10px;
}
}
My excuses in advance, since this seems to be a problem concerning very basic understanding of CSS and maybe also Javascript.
What I want to do is this: imagine a div which contains a h3 and a p. On hovering on the div I would like the h3 and p to change their font-weight. So far I am using this code here to change the opacity and border on hovering over the div, but I really don't know how I can refer to the two elements inside the div. I'm really sorry, but I need someone to explain it to me in very simple terms.
For example, I think those elements inside the div are called children, but I'm not even sure about that... I'm really working with all that HTML/CSS/Java stuff for the first time and try to figure things out as I go along. The tutorial sites I found so far couldn't solve my problem, therefore this post.
More background information: I'm using the "smoothgallery" script by jondesign (Jonathan Schemoul) () and am trying to bend it to my will, but that is pretty difficult if you don't have any clue how it actually works. The site I implemented the script in can be found here.
Here comes the CSS part that changes the div on hover:
.jdGallery .gallerySelector .gallerySelectorInner div.hover{
border: 1px solid #89203B;
border-left: 0.8em solid #89203B;
background: url('../../images/teaserBox_bg.jpg') no-repeat;
background-size: 100% 100%;
filter:alpha(opacity=1);
-moz-opacity:1; /
-khtml-opacity: 1;
opacity: 1;
}
This entry in the CSS file changes the settings for e.g. the h3 inside that div,
.jdGallery .gallerySelector .gallerySelectorInner div.galleryButton h3{
margin: 0;
padding: 0;
font-size: 12px;
font-weight: normal;
}
You may also want to take a look at the .js file that makes these classes, it can be found here.
This is probably the most important part here:
createGalleryButtons: function () {
var galleryButtonWidth =
((this.galleryElement.offsetWidth - 30) / 2) - 14;
this.gallerySet.each(function(galleryItem, index){
var button = new Element('div').addClass('galleryButton').injectInside(
this.gallerySelectorInner
).addEvents({
'mouseover': function(myself){
myself.button.addClass('hover');
}.pass(galleryItem, this),
'mouseout': function(myself){
myself.button.removeClass('hover');
}.pass(galleryItem, this),
'click': function(myself, number){
this.changeGallery.pass(number,this)();
}.pass([galleryItem, index], this)
}).setStyle('width', galleryButtonWidth);
galleryItem.button = button;
var thumbnail = "";
if (this.options.showCarousel)
thumbnail = galleryItem.elements[0].thumbnail;
else
thumbnail = galleryItem.elements[0].image;
new Element('div').addClass('preview').setStyle(
'backgroundImage',
"url('" + thumbnail + "')"
).injectInside(button);
new Element('h3').set('html', galleryItem.title).injectInside(button);
new Element('p').addClass('info').set('html', formatString(this.options.textGalleryInfo, galleryItem.elements.length)).injectInside(button);
}, this);
new Element('br').injectInside(this.gallerySelectorInner).setStyle('clear','both');
},
So my question here is, if it is possible at all to change the h3 and p settings by using the hover function on the main div?
Thanks in advance! Also for negative criticism, I don't really know if I did something wrong in the way I posted this question and if I can even ask it here.
You're making this way more complicated than it needs to be. No Javascript is required to do this. Let's say you've got the following:
<div class="container">
<h3>This is a header</h3>
<p>This is a paragraph</p>
</div>
So you've got a container, with a header and paragraph. Let's say you want to have the header normal weight, and the paragraph in red normally, with a padded box around the whole thing. Here are your styles:
.container { border: 1px solid black; padding: 10px; }
.container h3 { font-weight: normal; }
.container p { color: red; }
When you hover the mouse over the , you want the paragraph and header in bold and the box border to change to blue. Add this into your stylesheet (or <style> block) below the CSS above:
.container:hover { border-color: blue; }
.container:hover h3 { font-weight: bold; }
.container:hover p { font-weight: bold; }
Note that you can save a bit of space, and make it more concise by combining the <h3> and <p> styles into one line with a comma, since they're both the same. The whole thing would now look like this:
.container { border: 1px solid black; padding: 10px; }
.container h3 { font-weight: normal; }
.container p { color: red; }
.container:hover { border-color: blue; }
.container:hover h3, .container:hover p { font-weight: bold; }
Remember that the "C" in "CSS" stands for "cascading": styles cascade down through both hierarchies (that is, a parent element's style also applies to a child element, unless it's got default styles like margins or whatever), and down the style sheet - that means styles you define after others will override them if they apply to the same element.
The ":hover" selector in CSS can pretty much be used on anything, with very few exceptions. I use them regularly for Javascript-free drop-down menus. You can find more on the ":hover" CSS selector here: W3Schools CSS reference on ":hover". In fact, the W3Schools site is a generally great resource for brushing up your CSS.
because short answers what we always prefer to look for:
.classname :hover *