This question already has answers here:
CSS3's attr() doesn't work in major browsers
(5 answers)
Closed 5 years ago.
width: attr(data-width);
I want to know if there's any way it's possible to set a css value using HTML5's data- attribute the same way that you can set css content. Currently it doesn't work.
HTML
<div data-width="600px"></div>
CSS
div { width: attr(data-width) }
There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation
This fiddle should work like what you need, but will not for now.
Unfortunately, it's still a draft, and isn't fully implemented on major browsers.
It does work for content on pseudo-elements, though.
You can create with javascript some css-rules, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
var i = 101;
while (i--) {
addRule("[data-width='" + i + "%']", "width:" + i + "%");
}
This creates 100 pseudo-selectors like this:
[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }
Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.
As of today, you can read some values from HTML5 data attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data properties for setting the content.
Unfortunately it is not working for the width and height (tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).
But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width and data-height. You can find the GitHub repo to it here: cssattr.js.
Related
I was working on a Foundation 5 project that turned out to have an outdated _global.scss component. I was trying to get range sliders working, but they were mysteriously not. Turns out, I was missing the following 2 lines of CSS:
meta.foundation-data-attribute-namespace {
font-family: false;
}
Can someone explain these lines to me? The Docs say this:
// Used to provide media query values for javascript components.
// Forward slash placed around everything to convince PhantomJS to read the value.
meta.foundation-mq-small {
font-family: "/" + unquote($small-up) + "/";
width: lower-bound($small-range);
}
meta.foundation-mq-medium {
font-family: "/" + unquote($medium-up) + "/";
width: lower-bound($medium-range);
}
meta.foundation-mq-large {
font-family: "/" + unquote($large-up) + "/";
width: lower-bound($large-range);
}
meta.foundation-mq-xlarge {
font-family: "/" + unquote($xlarge-up) + "/";
width: lower-bound($xlarge-range);
}
meta.foundation-mq-xxlarge {
font-family: "/" + unquote($xxlarge-up) + "/";
width: lower-bound($xxlarge-range);
}
meta.foundation-data-attribute-namespace {
font-family: #{$namespace};
}
Thanks.
Some of Foundation's JavaScript needs to know about the different media query ranges definitions.
It is particularly true for some components such as interchange that is literally about things behaving differently depending on the viewport.
But foundation also lets you customize what the different breakpoints are.
In order to make have the value set in one single place, foundation uses this little trick of adding the media query breakpoint definition of a meta with a matching class name.
Here's how it works, for the breakpoint $small-up (it's the same for the others):
Let's say you keep the default value: $small-up: only screen.
The JS in foundation will do the following:
create a <meta> tag with the class .foundation-mq-small
read the value of the CSS property font-family
now it knows what is the definition of the $small-up media query
it's now accessible to the different foundation js components that may need it
You can see how it's done in foundation.js
The reason why it's using font-family is that it's one of the rare CSS properties that doesn't have a defined set of values. If they had used the property text-align, the browser would have ignored the invalid value and the JS would have gotten something like left in return.
How can I overwrite an entire CSS style for a class, id or other CSS selector?
For example:
If in styles1.css I have:
/* also, this file contains a lot of styles used on other pages */
.one-great-class {
background: white
...
/* a lot of properties */
}
... and in styles2.css (that is used only in one web page) I want to overwrite the class one-great-class completely what have I do to write?
.one-great-class {
/* Is possible that a line of code to delete all styles from this class? */
}
It's not possible in CSS at the moment.
But there may eventually be a property that does this: all
It can take three values:
initial | inherited | unset
Taken from the Cascading and Inheritance Module:
"For example, if an author specifies all: initial on an element it will block all inheritance and reset all properties, as if no rules appeared in the author, user, or user-agent levels of the cascade. "
According to the MDN documentation as of June 2017, all is currently supported by Chrome, Firefox/Mobile, and Opera. Safari supports only the CSS4 value revert, which is not supported by the other browsers.
.one-great-class {
border-radius: 50% 35% / 20% 25% 60%;
color: red;
font: 12px/14px Arial, serif;
height: 20em;
width: 20em;
/*... etc. */
}
.one-great-class {
all: initial;
}
Tested to work with IE9, Chrome and Opera. I had a problem with this when I wrote it, so decided that rather than changing existing rules, that I'd just append a new rule after the existing ones. From memory, the problem was with the default browser found in Android 2.3
Altering an existing rule seemed to be a better(cleaner) solution, though appending new rules ultimately proved to be chosen path. (I was changing background images by creating images with a canvas and then setting the background-image property. The images could be quite large, hence the preference for update)
Function
function replaceRuleAttrib(ruleSelector, attribText, newValue)
{
var nSheets, nRules, sheetNum, curSheet, curStyle, curAttrib;
var nSheets = document.styleSheets.length;
if (nSheets == 0)
document.head.appendChild(document.createElement('style'));
else
for (sheetNum = 0; sheetNum<nSheets; sheetNum++)
{
curSheet = document.styleSheets[sheetNum];
nRules = curSheet.cssRules.length;
for (ruleNum=0; ruleNum<nRules; ruleNum++)
{
curRule = curSheet.cssRules[ruleNum];
if (curRule.selectorText == ruleSelector)
{
for (styleI=0; styleI<curRule.style.length; styleI++)
{
styleName = curRule.style[styleI];
styleVal = curRule.style[styleName];
if (styleName == attribText)
{
curRule.style[styleName] = newValue;
return true;
}
}
}
}
}
document.styleSheets[0].insertRule( ruleSelector+'{' + attribText + ": " + newValue + "; }", 0);
}
Sample CSS (before)
<style>
h1
{
color: red;
}
</style>
Usage:
function onHeadingClick()
{
replaceRuleAttrib('h1', 'color', 'green');
}
Sample CSS (after)
<style>
h1
{
color: green;
}
</style>
Browser will apply css that come last.
.class {
font-size: 16px;
font-size: 14px;
}
The class will get font-size value 14px.
You can decleare a css as final.
.class {
font-size: 14px !important;
}
no genarel css rule can alter it.
Browser uses this method to give priority
inline < embeded < external < user-agent.
If you think you need more controll on css then use javascript to directly modfy dom.
Is there a way to style an ID based on a specific word in the ID name?
If I have something like this:
<div id="name-of-id.1234">Something</div>
<div id="name-of-id.5678">Something</div>
<div id="name-of-id.4321">Something</div>
Normally I'd style it like this:
div#name-of-id\.1234,
div#name-of-id\.5678,
div#name-of-id\.4321 {
color: #F0F;
}
But I'd MUCH RATHER do something like this:
div[# contains the word "name-of-id"] {
color: #F0F;
}
Is there a way to target a specific word in an ID like that?
I have very limited access to the html - I can add scripts/styles to the layout, but that's about it.
Use the CSS3 prefix substring matching attribute selector:
div[id^="name-of-id"] {
color: #F0F;
}
It is supported by all current browsers. For support in older version of IE, use the Selectivizr polyfill. There is also a selector for suffixes ([id$="..."]) and for general substrings ([id*="..."]).
If you can add javascript (and you use jQuery), you could add something like this:
$('div').each(function(){
if(this.id.match('name-of-id')) {
$(this).addClass('someClass');
}
});
Without jQuery, you could do:
var elems = document.getElementsByTagName('div');
for(var i=0; i<elems.length; i++) {
if(this.id.match('name-of-id')) {
this.className = this.className + 'someClass';
}
}
And then style them with a class:
.someClass {
/* your CSS styles */
}
Granted, running $('div') would be slow (as far as javascript is concerned) if your page contains a lot of them, so if you could narrow that selector down, this might be a more viable solution.
More to the point, there isn't a method I'm aware of to match partial ID names in CSS alone.
I want to use display: table and display: table-cell for my layout in browsers that support it. In IE7 I simply want to float my columns (since I assume it's not possible to get it to work in that browser), but cannot find anything about how to do it using Modernizr. Can anyone help me please?
I suppose I could use a browser conditional, but was hoping to not have to break out another CSS file.
Thanks!
If all you want to do is apply a single different rule for IE7 and less, I'd be tempted not to use Modernizr for this specific job.
Simply do something like this, to avoid having to "break out another CSS file":
#menu li {
display: table-cell;
*float: left;
}
This uses the Star Property Hack to provide a rule to only IE7 and below.
Another option is the !ie7 hack, which is for some odd reason my highest voted answer.
... And if you want to use Modernizr, you could use this snippet:
(function() {
var displayTests = ["table", "table-caption", "table-cell",
"table-column", "table-column-group", "table-footer-group",
"table-header-group", "table-row", "table-row-group"];
var rules = document.createElement("div").style;
for (var c=0; c<displayTests.length; c++) {
var testValue = displayTests[c];
Modernizr.addTest("display" + testValue, function() {
try {
rules.display = testValue;
return rules.display == testValue;
} catch (e) {
return false;
}
})
}
}());
Source [Link]
IE 8 does not tell the truth when the created element is a 'tfoot', and the display value is 'table-header-group'. The following snippet will not fail, even though IE 8 ignores the CSS setting and continues to display 'tfoot' below 'tbody'.
try {
var x = document.createElement('tfoot').style;
x.display = 'table-header-group';
console.log('Both IE 8 and Chrome end up here.');
} catch (e) {
console.log('Except IE 8 should have ended up here, since it does not move the tfoot element.');
}
It might be 'correct', in the sense that 'tfoot' has already set display to 'table-footer-group'; but it's 'wrong' in the sense that it (a) doesn't allow the user to override, and (b) doesn't tell the user that it isn't going to work. I haven't tested other browsers.
Please dont mind for adding a vulnarable content as below.
jffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
I have a multiline html text editor(tiny mce). When a user enters unappropriate words, as i entered above!. It will be saved properly in database. When i am trying to display the same data using a label. The displayed data disturbs the page design.
How can i fix this issue?
Please provide me a solution for this.
Thanks in advance
Regards,
Madhu BN
If it's about disturbing the page design when redisplaying the user's input and if the input is "inappropriate" then apply a CSS style to cut it off by using overflow:hidden.
<style>
.fixed { overflow:hidden; }
</style>
Then apply it to the div or container:
<div class="fixed" style="width:100px">The following input is really long and invalid.
fffffffffffffffffffffffffffffffffffffffffffffffffffffjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj</div>
This ensures the page layout is not disturbed. In the above example 100px is adhered to no matter the unbreaking length of the invalid text.
Edits:
If you want the wrapping behaviour try using CSS word-wrap: break-word;
<style>
.fixed {
word-wrap: break-word;
}
</style>
Or even put them both together to be really safe across browsers.
<style>
.fixed {
overflow:hidden;
word-wrap: break-word;
}
</style>
If you use PHP to print out the text, check out the wordwrap function.
Try inserting into the string. It's the HTML element for the "soft hyphen".
If using PHP, print(wordwrap($string, 75, ''));
More info on SO: Soft hyphen in HTML (<wbr> vs. )
This is a crossbrowser solution that I was looking at a little while ago that runs on the client and using jQuery:
(function($) {
$.fn.breakWords = function() {
this.each(function() {
if(this.nodeType !== 1) { return; }
if(this.currentStyle && typeof this.currentStyle.wordBreak === 'string') {
//Lazy Function Definition Pattern, Peter's Blog
//From http://peter.michaux.ca/article/3556
this.runtimeStyle.wordBreak = 'break-all';
}
else if(document.createTreeWalker) {
//Faster Trim in Javascript, Flagrant Badassery
//http://blog.stevenlevithan.com/archives/faster-trim-javascript
var trim = function(str) {
str = str.replace(/^\s\s*/, '');
var ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
};
//Lazy Function Definition Pattern, Peter's Blog
//From http://peter.michaux.ca/article/3556
//For Opera, Safari, and Firefox
var dWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT, null, false);
var node,s,c = String.fromCharCode('8203');
while (dWalker.nextNode()) {
node = dWalker.currentNode;
//we need to trim String otherwise Firefox will display
//incorect text-indent with space characters
s = trim( node.nodeValue ).split('').join(c);
node.nodeValue = s;
}
}
});
return this;
};
})(jQuery);
In javascript, add \u200b - Zero Width Space before displaying it
YOURTEXT=YOURTEXT.replace(/(.)/g,"\u200b$1");
You could use InsertAt repeatedly to achieve #Ryan's solution, or you could perform validation to prevent such malformed data from reaching the database.
Regular expressions would also make this available to put the soft-hyphen in.
It can be fixed with a little CSS using overflow-x (lots of cool examples after link).
Just make sure you specify a width, otherwise overflow-x won't do you any good.
Try it here
<style>
div{
width: 105px;
overflow-x: hidden;
float: left;
margin: 10px;
padding: 4px;
background: orange;
}
</style>
<div>WAYTOOLONGTOBESHOWN</div>
<div>WAYTOOLONGTOBESHOWN</div>