I have a page which contains charts etc for statistics which must be printable. I want to just use the standard browser print functionality in order to enable printing. I also have css which changes the button colours for selected buttons to make it clear which charts are being viewed. However, my issue is that when i attempt to print the page, this colouring is lost and reset to its default presentation.
I am aware of the capabilities of doing this in Chrome by using webkit-print-color-adjust settings in the CSS, however, the vast majority of users in my business use IE or Edge (as they are microsoft defaults) and therefore i need a solution which would work in them.
I have attempted using !important and #media print but to no effect as yet, unless i am using them wrong.
Here is the css currently:
#media print{
.btn-primary-chart:active,
.btn-primary-chart.active {
color: #ffffff;
background-color: green !important;
border-color: #285e8e;
}
}
Any help would be greatly appreciated :)
From the SO answer here, the reason why your CSS does not work is because of the default settings in the browser print settings.
With Chrome and Safari, you may want to add in
-webkit-print-color-adjust: exact;
to force print the background color.
There isn't any foolproof method to print backgrounds in Internet Explorer and Microsoft Edge yet. However, there's a few methods I've tried before and may work under some circumstances:
Method 1 (using sprite):
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#fffada', endColorstr='#fffada')";
Method 2:
CSS
.background:before {
content: '';
display: block;
position: absolute;
top: 0;
right: 0;
left: 0;
z-index: -1;
border-bottom: 1000px solid #eee;
}
HTML
<body class="background">
But if you want to print it yourself, you can enable 'Print Background Color':
To resolve this behavior, turn on the Print background colors and images option in Internet Explorer. To do this, follow these steps:
On the Tools menu, click Internet Options, and then click the Advanced tab.
In the Settings box, under Printing, click to select the Print background colors and images check box, and then click OK.
Also, a few similar StackOverFlow Posts
CSS #media print issues with background-color;
How can I force browsers to print background images in CSS?
Please try adding "!important" on the style (but not in the #media print).
I just met the problem that font color was missing in print view, and the final solution is replace
color: red !;
with
color: red !important;
in the style.
It seems that some styles will be ignored if "!important" is not used.
I found one solution that will even work in the EDGE browser. Here is the basic HTML:
<div style="position: relative;width:100%">
<div style="border-color:green;border-style:solid;
border-width:15px;width:70%;"></div>
<div style="position: absolute; top: 50%;
transform:translateY(-50%);left: 0px;">
Hello, world.
</div>
</div>
You can adjust the width or the parent and the child div's as necessary.
Worth mentioning here, since I had a similar problem, is that EDGE will render SVG properly while ignoring the HTML background-color.
So instead of using:
<div style="background-color:red; width:20px height:20px">...</div>
You can use something like this:
<svg style="width:20px;height:20px">
<rect width="100%" height="100%" style="fill:red">
</svg>
Actually it is possible to programmatically change the background printing setting for IE:
void CMeetingScheduleAssistantApp::SetPrintBackgroundSetting(CSettingsStore& regSettings, CString strPrintBackground, BOOL& rbResetDefault, BOOL& rbReset)
{
rbResetDefault = FALSE;
rbReset = FALSE;
// Attempt to read the registry key value
if(regSettings.Read(_T("Print_Background"), strPrintBackground))
{
// Update registry key value if we need to
if (strPrintBackground != _T("yes"))
{
regSettings.Write(_T("Print_Background"), _T("yes"));
// Remember, reset it back to original value afterwards
rbReset = true;
}
}
else
{
// User accepted default behavior, so create registry key value
regSettings.Write(_T("Print_Background"), _T("yes"));
// Remember, reset it back to default value afterwards
rbResetDefault = true;
}
}
void CAvailableBrothersReportPreview::OnButtonPrintPreview()
{
CSettingsStore regSettings(false, false);
if (regSettings.Open(_T("SOFTWARE\\MICROSOFT\\Internet Explorer\\Main")))
{
CString strPrintBackground;
BOOL bResetValue = FALSE, bResetResetDefault = FALSE;
// Try to revise the Print_Background setting
CMeetingScheduleAssistantApp::SetPrintBackgroundSetting(regSettings, strPrintBackground,
bResetResetDefault, bResetValue);
// Now show the print preview dialogue
if (m_pHtmlView != nullptr)
m_pHtmlView->DoPrintPreview();
// Reset the Print_Background setting if required
if (bResetValue)
regSettings.Write(_T("Print_Background"), strPrintBackground);
else if (bResetResetDefault)
regSettings.Write(_T("Print_Background"), _T("no"));
}
}
Related
Is there any way to use conditional statements in CSS?
I'd say the closest thing to "IF" in CSS are media queries, such as those you can use for responsive design. With media queries, you're saying things like, "If the screen is between 440px and 660px wide, do this". Read more about media queries here: http://www.w3schools.com/cssref/css3_pr_mediaquery.asp, and here's an example of how they look:
#media screen and (max-width: 300px) {
body {
background-color: lightblue;
}
}
That's pretty much the extent of "IF" within CSS, except to move over to SASS/SCSS (as mentioned above).
I think your best bet is to change your classes / IDs within the scripting language, and then treat each of the class/ID options in your CSS. For instance, in PHP, it might be something like:
<?php
if( A > B ){
echo '<div class="option-a">';
}
else{
echo '<div class="option-b">';
}
?>
Then your CSS can be like
.option-a {
background-color:red;
}
.option-b {
background-color:blue;
}
No. But can you give an example what you have in mind? What condition do you want to check?
Maybe Sass or Compass are interesting for you.
Quote from Sass:
Sass makes CSS fun again. Sass is CSS, plus nested rules, variables, mixins, and more, all in a concise, readable syntax.
CSS itself doesn't have conditional statements, but here's a hack involving custom properties (a.k.a. "css variables").
In this trivial example, you want to apply a padding based on a certain condition—like an "if" statement.
:root { --is-big: 0; }
.is-big { --is-big: 1; }
.block {
padding: calc(
4rem * var(--is-big) +
1rem * (1 - var(--is-big))
);
}
So any .block that's an .is-big or that's a descendant of one will have a padding of 4rem, while all other blocks will only have 1rem. Now I call this a "trivial" example because it can be done without the hack.
.block {
padding: 1rem;
}
.is-big .block,
.block.is-big {
padding: 4rem;
}
But I will leave its applications to your imagination.
The #supports rule (92% browser support July 2017) rule can be used for conditional logic on css properties:
#supports (display: -webkit-box) {
.for_older_webkit_browser { display: -webkit-box }
}
#supports not (display: -webkit-box) {
.newer_browsers { display: flex }
}
The only conditions available in CSS are selectors and #media. Some browsers support some of the CSS 3 selectors and media queries.
You can modify an element with JavaScript to change if it matches a selector or not (e.g. by adding a new class).
I would argue that you can use if statements in CSS. Although they aren't worded as such. In the example below, I've said that if the check-box is checked I want the background changed to white. If you want to see a working example check out www.armstrongdes.com. I built this for a client. Re size your window so that the mobile navigation takes over and click the nav button. All CSS. I think it's safe to say this concept could be used for many things.
#sidebartoggler:checked + .page-wrap .hamb {
background: #fff;
}
// example set as if statement sudo code.
if (sidebaretoggler is checked == true) {
set the background color of .hamb to white;
}
CSS has become a very powerful tool over the years and it has hacks for a lot of things javaScript can do
There is a hack in CSS for using conditional statements/logic.
It involves using the symbol '~'
Let me further illustrate with an example.
Let's say you want a background to slide into the page when a button is clicked. All you need to do is use a radio checkbox.
Style the label for the radio underneath the button so that when the button is pressed the checkbox is also pressed.
Then you use the code below
.checkbox:checked ~ .background{
opacity:1
width: 100%
}
This code simply states IF the checkbox is CHECKED then open up the background ELSE leave it as it is.
css files do not support conditional statements.
If you want something to look one of two ways, depending on some condition, give it a suitable class using your server side scripting language or javascript. eg
<div class="oh-yes"></div>
<div class="hell-no"></div>
There is no native IF/ELSE for CSS available. CSS preprocessors like SASS (and Compass) can help, but if you’re looking for more feature-specific if/else conditions you should give Modernizr a try. It does feature-detection and then adds classes to the HTML element to indicate which CSS3 & HTML5 features the browser supports and doesn’t support. You can then write very if/else-like CSS right in your CSS without any preprocessing, like this:
.geolocation #someElem {
/* only apply this if the browser supports Geolocation */
}
.no-geolocation #someElem {
/* only apply this if the browser DOES NOT support Geolocation */
}
Keep in mind that you should always progressively enhance, so rather than the above example (which illustrates the point better), you should write something more like this:
#someElem {
/* default styles, suitable for both Geolocation support and lack thereof */
}
.geolocation #someElem {
/* only properties as needed to overwrite the default styling */
}
Note that Modernizr does rely on JavaScript, so if JS is disabled you wouldn’t get anything. Hence the progressive enhancement approach of #someElem first, as a no-js foundation.
Changing your css file to a scss file would allow you to do the trick. An example in Angular would be to use an ngClass and your scss would look like:
.sidebar {
height: 100%;
width: 60px;
&.is-open {
width: 150px
}
}
While this feels like a bit of a hack, and may not work perfectly in all browsers, a method I have used recently combines the fact that CSS (at least in Chrome) seems to ignore invalid values set on properties, and we can set custom properties that fall back to their default value when invalid.
(Note: I haven't deeply tested this, so treat it as a hacky proof of concept/possible idea)
The following is written in SCSS, but it should work just as well in standard CSS:
.hero-image {
// CSS ignores invalid property values
// When this var is set to an image URL, the browser will ignore it
// When this var isn't set, then we will use the default fallback for the var, which is 'none'
display: var(--loading-page-background-image, none);
// This part isn't directly relevant to my 'if' example, but shows how I was actually using this custom property normally
background-image: var(--loading-page-background-image, none);
}
I'm setting the custom property from JavaScript / React, but it would likely work regardless of how you set it:
// 'true' case
const chosenLoaderUrl = "https://www.example.com/loader.png";
// 'false' case
//const chosenLoaderUrl = "";
// containerRef is just a reference to the div object, you could get this with
// jquery or however you need. Since I'm in React, I used useRef() and attached
// that to my div
containerRef.current.style.setProperty(
"--loading-page-background-image",
`url(${chosenLoaderUrl})`
);
When chosenLoaderUrl is set to my url, that url is an invalid value for the display property, so it seems to get ignored.
When chosenLoaderUrl is set to an empty value, it falls back to the default value in my var() statement, so sets display to none
I'm not sure how 'generalisable' this concept it, but figured I would add it to the other suggestions here in case it is useful to anyone.
Your stylesheet should be thought of as a static table of available variables that your html document can call on based on what you need to display. The logic should be in your javascript and html, use javascript to dynamically apply attributes based on conditions if you really need to. Stylesheets are not the place for logic.
You can use combination of jquery and css classes i.e. I want to change a font color of certain element depending on the color of the background:
CSS:
.h3DarkMode{
color: lightgray;
}
.h3LightMode{
color: gray;
}
HTML:
<h3 class="myText">My Text Here...</h3>
JQuery:
var toggleMode = localStorage.getItem("toggleMode");
if (toggleMode == "dark"){
$(".myText").removeClass("h3LightMode").addClass("h3DarkMode");
}else{
$(".myText").removeClass("h3DarkMode").addClass("h3LightMode");
}
No you can't do if in CSS, but you can choose which style sheet you will use
Here is an example :
<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]-->
will use only for IE 6 here is the website where it is from http://www.quirksmode.org/css/condcom.html , only IE has conditional comments. Other browser do not, although there are some properties you can use for Firefox starting with -moz or for safari starting with -webkit. You can use javascript to detect which browser you're using and use javascript if for whatever actions you want to perform but that is a bad idea, since it can be disabled.
I know there's a lot of questions about this, but I tried everything and nothing seems to work. I followed these links:
Splitting HTML page so Printer splits it into separate pages
Chrome: Print preview differs from simulate CSS media print
Print media queries being ignored in Chrome?
Google Chrome Printing Page Breaks
and much more.
I tried pretty much every single suggestion in all of them.
Here's what I've got so far :
html
<link href="path/styles/print.css" rel="stylesheet" media="print">
<div class="page-break">
//some stuff
</div>
css
#media all {
.page-break { display: none; }
}
#media print {
.page-break { display: block; page-break-before: always;}
}
In IE and FF, I can't see preview of the page I'll print, but when I do print, it works just fine. In chrome, I can see preview, but it's never right... next I'm trying to save it as pdf, but it still doesn't apply print css.
*Saving as pdf as nothing to do with trying to make it works... it's just to save paper
Now, before you post an answer, please be aware of the following :
I tried this:
!important; hack
Deleting css page and put css directly in html page
Delete media all
Delete media all and changing display block to none
Tried page-break-inside: avoid;
*{transition:none !important;}
.page-break { ... transition: none !important;}
put it in main style sheet
float: none !important;
position: relative; position: static;
display: block; display: inline;
box-sizing: content-box;
-webkit-region-break-inside: avoid;
I didn't try with other version of Chrome. I tried on v.50, after multiple attempt fail, I updated to v.51. Some said it works on v.38 or something like that... I won't downgrade to that version.
Edit: I forgot to mention that my html code is in a jsp page. So the <div class="page-break"> is in a for-loop. Every loop has to be on individual page.
Edit 2: I created a jsfiddle. I pasted the source code I have and it works perfectly. So I removed the css stylesheet that are links in my page. But even by doing that, it won't work. So if it's override somewhere, it's not there.
The page is a JSP page, does it have anything to do about it? If not I'm clueless, because in the same project, on the page I want to print, I added a button that redirect to a page.html and I created 3 divs with the same class name and it works just fine.
So! I'm here to answer my own question, in case someone just can't make it work just like me.
I tried to give a new approach to my problem, since I can't print single div per page and I don't know why, I must find another way. But it's not that I didn't know how it works... I created a JSFiddle and it worked. In my own project, I created a html page and it worked. But since I was in JSP, maybe it was messing with my code somewhere.. I have no idea.
So here's what I've done.
function getStuffToPrint(data){
var html = "", index, len;
for (index = 0, len = data.length; index < len; ++index) {
html += "<div class=\"custom-page-break\">" + data[index].innerHTML + "</div>";
}
var mywindow = window.open();
mywindow.document.write('<html><head>');
mywindow.document.write('<link href="my/path/to/styles/print.css" rel="stylesheet" type="text/css"/>');
mywindow.document.write('</head><body >');
mywindow.document.write(html);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
return true;
}
In my case, data was an objectHTMLCollection : document.getElementsByClassName("custom-page-break")
It's a bit ratchet, I had to write the div with the class name again...
Here's my css, it may work without display: block and page-break-inside, I didn't even try.
#media print {
.custom-page-break {
display: block !important;
page-break-before: always !important;
page-break-inside: avoid !important;
}
}
Hope it'll save hours for some people.
Have you tried to put the print.css in your main style css document ? I had a similar case and it solved my problem.
You dont have to make a pdf file every time to see if the #media print worked, you can see the page emulated like print in your Google developpement tool on Chrome:
To see that option, do : F12 -> show console -> rendering ( it's a tab of the console ) -> check "Emulate media Print".
I am programming CSS for a symfony2 project. This project is already far programmed.
Now I added some div´s and a table. The table I can design more or less, but when I create new div´s and want to set these like:
div {
background: #f00;
color: #eee;
}
The browser shows nothing about these settings. They are shown in the HTML of the Browser but are totally not setted.
stupid mistake in css.
I made a comment before the first rule with two slashes:
//comment
.rule {
property: value;
}
which made probably skip the next rule and the browser didn´t rendered it as code. so just edited the comment from two slashes to /* comment */ and everything is good.
Does iBooks add something like a CSS class or anything else in order to be able to style some sections of the book differently (in lighter colors) when the night mode is active?
iBooks adds a __ibooks_internal_theme attribute to the :root (html) element with a value that's changing with the theme selected.
Go ahead with this:
:root[__ibooks_internal_theme*="Sepia"]
:root[__ibooks_internal_theme*="Night"]
You can find more details on GitHub: theme-detect.css
I will eventually add details on CSS limitations for the three themes.
Computed Styles
You could try doing a window.getComputedStyle(document.body).backgroundColor. This is not tested.
EDIT: Concerning getComputedStyle, my mistake--background color (assuming that's what iBooks is using) is NOT inherited, so getComputedStyle is not going to buy you anything. Since styling on the HTML element has different levels of support (HTML4 technically doesn't even allow a style attribute on the HTML element AFAIK), it is theoretically possible that your inherit trick did not work. I'd stick in a
alert(document.documentElement.style.backgroundColor);
and see what pops up. Another brute-force approach is to do a
alert(document.documentElement.outerHTML);
You'll get a huge amount of stuff in the alert box but it should scroll for you and you might be able to see something useful in there.
FWIW, Readium apparently does night mode with a background-color of rgb(20,20,20) on the html element.
Media Queries
It is reported that Apple has introduced proprietary media queries "paginated" and "nonpaginated" to detect whether the user is using the new scrolling mode in iBooks 3.0. It is possible that it has introduced a media query for the dark theme (actually called "night"), but I'm just guessing. In any way, there's no way to my knowledge to enumerate media queries, and so it would be a process of pure trial and error trying to find it.
Without the help of iBooks, you can add another css for night mode. Just add this tag inside the
<link rel="stylesheet" href="nightmode.css" class="night" />
Another solution is to make Custom Media Queries into your css file:
/* Sepia */
#media sepia {
* { color: #000000; }
body { background-color: #eae4d3; }
}
/* Black */
#media black {
* { color: #ffffff; }
body { background-color: #000000; color: #ffffff; }
}
/* White */
#media white {
* { color: #000000; }
body { background-color: #ffffff; }
}
I have a textfield is there a way to hide the blinking text cursor? I say this because I am doing a horror/mystery website and one of the clues is to start typing anywhere.
Maybe I can do it with javascript?
The basic idea is, that the cursor's color is the same as the text's color. So the first thing you do is make the text transparent, thus taking the cursor away with it. Then you can make the text visible again with a text shadow.
Use this link to see it live in jsfiddle.
input[type="text"]{
color : transparent;
text-shadow : 0 0 0 #000;
}
input[type="text"]:focus{
outline : none;
}
Update:
Known to not work in iOS 8 and IE 11
Another idea of my is a bit more hacky and requires javascript.
HTML and CSS part:
You make 2 input fields and position one exactly on top of the another with z-index, etc. Then you make the top input field completely transparent, no focus, no color, and alike.
You need to set the visible, lower input to disabled, so that it only shows the content of the above input, but not actually works.
Javascript part:
After all the above you sync the two inputs. On keypress or on change you copy the contents of the higher input to the lower.
Summing all the above: you type in an invisible input, and that will be sent to the backend when the form submitted, but every update of the text in it will be echoed into the lower visible, but disabled input field.
caret-color: transparent !important; works in newer browsers
Try this:
$(document).ready(
function() {
$("textarea").addClass("-real-textarea");
$(".textarea-wrapper").append("<textarea class=\"hidden\"></textarea>");
$(".textarea-wrapper textarea.hidden").keyup(
function() {
$(".textarea-wrapper textarea.-real-textarea").val($(this).val());
}
);
$(".textarea-wrapper textarea.-real-textarea").focus(
function() {
$(this).parent().find("textarea.hidden").focus();
}
);
}
);
.textarea-wrapper {
position: relative;
}
.textarea-wrapper textarea {
background-color: white;
}
.textarea-wrapper,
.textarea-wrapper textarea {
width: 500px;
height: 500px;
}
.textarea-wrapper textarea.hidden {
color: white;
opacity: 0.00;
filter: alpha(opacity=00);
position: absolute;
top: 0px;
left: 0px;
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div class="textarea-wrapper">
<textarea></textarea>
</div>
The idea is to create a second, invisible <textarea> over/on-top-of the real one. The user is typing in the invisible one but the text doesn't appear (nor the caret/cursor) as it is invisible! You then use JavaScript to assign its value to the visible one.
But it doesn't seem to work in IE8 :'( the caret is still visible even though the opacity is cranked up to 11.
But it works in Firefox... ?
I was looking for a way to hide the blinking cursor on iOS devices for date inputs that trigger a calendar, because you could see the cursor blinking on top of the calendar picker.
input:focus { text-indent: -9999em; }
So in this case my CSS works nicely, obviously the downside is that if you need to see what you are typing then it is not good
I think this is a perfect solution:
make the input wide enough, align right to screen right, thus make cursor and content locate at the outside of the screen, while it's still clickable
Unfortunately you can not style the text cursor with CSS. You can only do some very bad JavaScript tricks but depending on the layout and requirements of your website, it might not be possible at all. So I would recommend to forget the whole idea.
<input style="position: fixed; top: -1000px">
Works in iOS8.
you can "Hide textfield blinking cursor" by calling blur function on focus event
<input type="text" onfocus="this.blur()"/>
function noCursor(a){
var a = document.getElementById(a),
b = document.createElement('input');
b.setAttribute("style","position: absolute; right: 101%;");
a.parentNode.insertBefore(b, a);
if(a.addEventListener){
b.addEventListener("input",function(){a.value = b.value});
a.addEventListener("focus",function(){b.focus()});
}else{
a.attachEvent("onfocus",function(){b.focus()});
b.attachEvent("onpropertychange",function(){a.value = b.value});
};
}
noCursor('inp');
<input id="inp">
You can use the function for each element jou want no cursor for.
Setting the input to readonly also does this since it prevents focus but it may not be applicable to many use cases that still need it.
<input type="text" readonly />
List of recommended css solutions to hide the caret
caret-color: transparent; - For my case this approach wasn't good enough since you're still able to manipulate the input field in order to show the caret on ios. You can reproduce it on an ipad by focusing on an input then press the keyboard button that brings the keyboard down. After that you can simply just click on the input field again and suddenly the caret appears. I have also been able to see the cursor on iphones but i'm not exactly sure how to reproduce it since it seems kind of random.
opacity: 0 - This approach does not work on android devices since you won't be able to focus on the input. Another thing I don't like is the fact that the site wouldn't automatically scroll up/down to the input after focusing.
text-indent: -9999em; - This isn't really a solution in itself since the caret always would be in the left upper corner of the input, atleast on ios devices. Though if you set the width of the input to overflow the website's width then you wouldn't be able to see the caret.
visibility: hidden; display: none; - These solutions do remove the caret but you'll not be able to focus on the input, not even if you've implemented a click event to do it.
font-size: 0; - I do not recommend this approach since it doesn't work on adroid devices and apparently some windows computers. The browser will also zoom in on the input if the font-size is less than 16px therefore you would have to add maximum-scale=1 to the meta viewport tag. You would also have to display the input somewhere else than the input field.
What I did
I ended up not using any of these methods since they didn't work well for my project. I instead used a lightweight code editor like Lajos Mészáros also recommended and made the height of the input 0. That also means you'll need to make a click event on another element that sets the focus for the input. You can look at Monkeytype for reference (I'm not affiliated to that website).
just made a proof of concept for a friend of mine, using #sinfere 's idea:
demo: http://jsfiddle.net/jkrielaars/y64wjuhj/4/
The start of the input is offset so it falls outside of the container (which has overflow hidden)
The actual caracters (and blinking cursor) wil never enter into view.
The fake div is placed below the input field so a tap on the fake div will set focus on the invisible input.
<div class="container">
<div id="fake" class="fake">
<span class='star empty'></span>
<span class='star empty'></span>
<span class='star empty'></span>
<span class='star empty'></span>
</div>
<input type="text" id="password" class="invisible" maxlength="4">
</div>