I am trying to print a page. In that page I have given a table a background color.
When I view the print preview in chrome its not taking on the background color property...
So I tried this property:
-webkit-print-color-adjust: exact;
but still its not showing the color.
http://jsfiddle.net/TbrtD/
.vendorListHeading {
background-color: #1a4567;
color: white;
-webkit-print-color-adjust: exact;
}
<div class="bs-docs-example" id="soTable" style="padding-top: 10px;">
<table class="table" style="margin-bottom: 0px;">
<thead>
<tr class="vendorListHeading" style="">
<th>Date</th>
<th>PO Number</th>
<th>Term</th>
<th>Tax</th>
<th>Quote Number</th>
<th>Status</th>
<th>Account Mgr</th>
<th>Shipping Method</th>
<th>Shipping Account</th>
<th style="width: 184px;">QA</th>
<th id="referenceSO">Reference</th>
<th id="referenceSO" style="width: 146px;">End-User Name</th>
<th id="referenceSO" style="width: 118px;">End-User's PO</th>
<th id="referenceSO" style="width: 148px;">Tracking Number</th>
</tr>
</thead>
<tbody>
<tr class="">
<td>22</td>
<td>20130000</td>
<td>Jim B.</td>
<td>22</td>
<td>510 xxx yyyy</td>
<td>zznn#abc.co</td>
<td>PDF</td>
<td>12/23/2012</td>
<td>Approved</td>
<td>PDF</td>
<td id="referenceSO">12/23/2012</td>
<td id="referenceSO">Approved</td>
</tr>
</tbody>
</table>
</div>
The CSS property print-color-adjust: exact; works appropriately.
However, making sure you have the correct CSS for printing can often be tricky. Several things can be done to avoid the difficulties you are having. First, separate all your print CSS from your screen CSS. This is done via the #media print and #media screen.
Often times just setting up some extra #media print CSS is not enough because you still have all your other CSS included when printing as well. In these cases you just need to be aware of CSS specificity as the print rules don't automatically win against non-print CSS rules.
In your case, the print-color-adjust: exact is working. However, your background-color and color definitions are being beaten out by other CSS with higher specificity.
While I do not endorse using !important in nearly any circumstance, the following definitions work properly and expose the problem:
#media print {
tr.vendorListHeading {
background-color: #1a4567 !important;
print-color-adjust: exact;
}
}
#media print {
.vendorListHeading th {
color: white !important;
}
}
Here is the fiddle (and embedded for ease of print previewing).
That CSS property is all you need it works for me...When previewing in Chrome you have the option to see it BW and Color(Color: Options- Color or Black and white) so if you don't have that option, then I suggest to grab this Chrome extension and make your life easier:
https://chrome.google.com/webstore/detail/print-background-colors/gjecpgdgnlanljjdacjdeadjkocnnamk?hl=en
The site you added on fiddle needs this in your media print css (you have it just need to add it...
media print CSS in the body:
#media print {
body {-webkit-print-color-adjust: exact;}
}
UPDATE
OK so your issue is bootstrap.css...it has a media print css as well as you do....you remove that and that should give you color....you need to either do your own or stick with bootstraps print css.
When I click print on this I see color....
http://jsfiddle.net/rajkumart08/TbrtD/1/embedded/result/
Chrome will not render background-color, or several other styles, when printing if the background graphics setting is turned off.
This has nothing to do with css, #media, or specificity. You can probably hack your way around it, but the easiest way to get chrome to show the background-color and other graphics is to properly check this checkbox under More Settings.
I just needed to add the !important attribute onto the the background-color tag in order for it to show up, did not need the webkit part:
background-color: #f5f5f5 !important;
Your CSS must be like this:
#media print {
body {
-webkit-print-color-adjust: exact;
}
}
.vendorListHeading th {
background-color: #1a4567 !important;
color: white !important;
}
FOR THOSE USING BOOTSTRAP.CSS, this is the fix!
I have tried all the solutions and they weren't working... until I discovered that bootstrap.css had a super annoying #media print that resets all your colors, background-colors, shadows, etc...
#media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}
So either remove this section from bootstrap.css (or bootstrap.min.css)
Or override these values in the css of the page you want to print in your own #media print
#media print {
body {
-webkit-print-color-adjust: exact;
}
.customClass{
//customCss + !important;
}
//more of your custom css
}
For IE
If you are using IE then go to print preview ( right click on document -> print preview ), go to settings and there is option "print background color and images", select that option and try.
If you are using bootstrap or any other 3rd party CSS, make sure you specify the media screen only on it, so you have the control of the print media type in your own CSS files:
<link rel="stylesheet" media="screen" href="">
if you are using Bootstrap.just use this code in your custom css file. Bootstrap removes all your colors in print preview.
#media print{
.box-text {
font-size: 27px !important;
color: blue !important;
-webkit-print-color-adjust: exact !important;
}
}
Are your sure this is a css issue ? There are some posts on google around this issue:
http://productforums.google.com/forum/#!category-topic/chrome/discuss-chrome/eMlLBcKqd2s
It may be related to the print process. On safari, which is webkit also, there is a checkbox to print background images and colors in the printer dialog.
Use the following in your #media print style sheet.
h1 {
background-color:#404040;
background-image:url("img/404040.png");
background-repeat:repeat;
box-shadow: inset 0 0 0 1000px #404040;
border:30px solid #404040;
height:0;
width:100%;
color:#FFFFFF !important;
margin:0 -20px;
line-height:0px;
}
Here are a couple things to note:
background-color is the absolute fallback and is there for posterity mostly.
background-image uses a 1px x 1px pixel of #404040 made into a PNG. If the user has images enabled it may work, if not...
Set the box-shadow, if that doesn't work...
Border = 1/2 your desired height and/or width of box, solid, color. In the example above I wanted a 60px height box.
Zero out the heigh/width depending on what you're controlling in the border attribute.
Font color will default to black unless you use !important
Set line-height to 0 to fix for the box not having physical dimension.
Make and host your own PNGs :-)
If the text in the block needs to wrap, put it in a div and position the div using position:relative; and remove line-height.
See my fiddle for a more detailed demonstration.
There's a style in the bootstrap css files under #media print{*,:after,:before ....} that has color and background styles labeled !important, which remove any background colors on any elements. Kill those two pieces of css and it will work.
Bootstrap is making the executing decision that you should never have any background color in prints, so you have to edit their css or have another !important style that is a higher precedence. Good job bootstrap...
I used purgatory101's answer but had trouble keeping all colours (icons, backgrounds, text colours etc...), especially that CSS stylesheets cannot be used with libraries which dynamically change DOM element's colours. Therefore here is a script that changes element's styles (background-colour and colour) before printing and clears styles once printing is done. It is useful to avoid writing a lot of CSS in a #media print stylesheet as it works whatever the page structure.
There is a part of the script that is specially made to keep FontAwesome icons color (or any element that uses a :before selector to insert coloured content).
JSFiddle showing the script in action
Compatibility: works in Chrome, I did not test other browsers.
function setColors(selector) {
var elements = $(selector);
for (var i = 0; i < elements.length; i++) {
var eltBackground = $(elements[i]).css('background-color');
var eltColor = $(elements[i]).css('color');
var elementStyle = elements[i].style;
if (eltBackground) {
elementStyle.oldBackgroundColor = {
value: elementStyle.backgroundColor,
importance: elementStyle.getPropertyPriority('background-color'),
};
elementStyle.setProperty('background-color', eltBackground, 'important');
}
if (eltColor) {
elementStyle.oldColor = {
value: elementStyle.color,
importance: elementStyle.getPropertyPriority('color'),
};
elementStyle.setProperty('color', eltColor, 'important');
}
}
}
function resetColors(selector) {
var elements = $(selector);
for (var i = 0; i < elements.length; i++) {
var elementStyle = elements[i].style;
if (elementStyle.oldBackgroundColor) {
elementStyle.setProperty('background-color', elementStyle.oldBackgroundColor.value, elementStyle.oldBackgroundColor.importance);
delete elementStyle.oldBackgroundColor;
} else {
elementStyle.setProperty('background-color', '', '');
}
if (elementStyle.oldColor) {
elementStyle.setProperty('color', elementStyle.oldColor.value, elementStyle.oldColor.importance);
delete elementStyle.oldColor;
} else {
elementStyle.setProperty('color', '', '');
}
}
}
function setIconColors(icons) {
var css = '';
$(icons).each(function (k, elt) {
var selector = $(elt)
.parents()
.map(function () { return this.tagName; })
.get()
.reverse()
.concat([this.nodeName])
.join('>');
var id = $(elt).attr('id');
if (id) {
selector += '#' + id;
}
var classNames = $(elt).attr('class');
if (classNames) {
selector += '.' + $.trim(classNames).replace(/\s/gi, '.');
}
css += selector + ':before { color: ' + $(elt).css('color') + ' !important; }';
});
$('head').append('<style id="print-icons-style">' + css + '</style>');
}
function resetIconColors() {
$('#print-icons-style').remove();
}
And then modify the window.print function to make it set the styles before printing and resetting them after.
window._originalPrint = window.print;
window.print = function() {
setColors('body *');
setIconColors('body .fa');
window._originalPrint();
setTimeout(function () {
resetColors('body *');
resetIconColors();
}, 100);
}
The part that finds icons paths to create CSS for :before elements is a copy from this SO answer
I tried all suggested solutions here (and in many other questions), such as applied background-color: #000 !important; both in stylesheet and inline, or set
#media print {
* {
color-adjust: exact !important;
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
}
, even combined them together, but nothing worked.
After hours of researching without any results, I recognized that the "bug" lost background-color only appears on table (th, td), but other HTML elements (div,...) or other CSS attributes (border-color,...) still work.
Therefore, I came up with a "hack" to wrap-up anything inside <th> or <td> with a <div> (you can adjust padding to make it display same as prior).
Here I used React and makeStyles of #material-ui/core.
JSX:
<Table bordered>
<thead className={classes.thead}>
<tr>
<th><div>Col 1</div></th>
<th><div>Col 2</div></th>
<th><div>Col 3</div></th>
</tr>
</thead>
<tbody>
<tr>
<td className={classes.tdGreen}><div>Row 1 - Col 1</div></td>
<td><div>Row 1 - Col 2</div></td>
<td><div>Row 1 - Col 3</div></td>
</tr>
<tr>
<td><div>Row 2 - Col 1</div></td>
<td className={classes.tdBlue}><div>Row 2 - Col 2</div></td>
<td><div>Row 2 - Col 3</div></td>
</tr>
</tbody>
</Table>
Styles:
const useStyles = makeStyles(() => ({
thead: {
textAlign: 'center',
'& th:not(:last-child)': {
padding: '0',
'& > div': {
padding: '.75rem',
backgroundColor: '#D8D8D8 !important',
}
}
},
tdGreen: {
padding: '0 !important',
'& > div': {
padding: '.75rem',
color: 'white',
backgroundColor: 'green !important',
}
},
tdBlue: {
padding: '0 !important',
'& > div': {
padding: '.75rem',
color: 'white',
backgroundColor: 'blue !important',
}
}
}));
You can take the idea and convert it into pure HTML/CSS solutions.
Hope this can help anyone struggled with this issue!
You can also use the box-shadow property.
The best solution for this if you are using bootstrap so just do one thing remove #media print {} all code inside this. and enable background graphics from more settings while taking print preview.
You can use inline css styles with !important.
Eg.
<p style="background:red!important">ABCD</p>
If you are using nextjs or react add this to the global css:
#media print {
body {
-webkit-print-color-adjust: exact;
}
}
This worked for me.
you can download bootstrap 4 css from bootstrap web and looking on the bottom code
look where code is
and remove this css style because this override your css color table style
If you download Bootstrap without the "Print media styles" option, you will not have this problem and do not have to remove the "#media print" code manually in your bootstrap.css file.
I double load my external css source file and change the media="screen" to media="print" and all the borders for my table were shown
Try this :
<link rel="stylesheet" media="print" href="bootstrap.css" />
<link rel="stylesheet" media="screen" href="bootstrap.css" />
I am working on a PHP script that takes a plain text file task list and parses things like:
Project name heading because it ends with a semi-colon: == a project
Tasks begin with a - task name
#tag-name gets wrapped with <span class="tag">#tag-name</span>
#done gets wrapped with <span class="tag done">#done</span>
and more
This PHP function below is what does the replacements...
function get_marked_up_todo($todo){
$todo = htmlspecialchars($todo,ENT_QUOTES)."\n\n";
$search = array('/(.+:)(.+)\n\n/sU', // Get projects
'/(- ([^\#\n]+).+)/', // Get todos
'/(.+:)/', // Get headings
'/\n([^\<\n].+)/', // Get notes
'/- (.+#done)/', // Get done
'/(#due\([^\)]+\))/', // Get due tags
'/(#(?!due)[^\s]+)/', // Get tags
"/\t/",
'/`(.*?)`/', // inline code
);
$replace = array("<div class=\"project\">\n$1$2\n</div>\n\n",
'<span class="todo"><input type="checkbox" value="'.trim('\2').'"> \1</span>',
'<h1>\1</h1>',
"\n\t<span class=\"note\">$1</span>",
'<span class="bullet-done">? ? ??</span> - <strike>\1</strike>',
'<span class="tag due">\1</span>',
'<span class="tag">\1</span>',
"\t<span class=\"tab\"></span>",
'<code>\1</code>',
);
return preg_replace($search, $replace, $todo);
}
In the above search and replace arrays the very last item in both arrays is a new pattern I added to find inline code wrapped in backticks like Markdown inline code.
The problem is, on the output each task item row gets a checkbox input field added to the front of the task row and in the value of this checkbox my code is being parsed.
All the other replacement RegEx does not show up in the checkbox values only when I add an item like this inline code or any other item I have added such as RegEx for bold text and italic.
Why does mine show up in the checkbox value HTML and none of the others do?
I have setup a demo to show the output here of the PHP -
https://3v4l.org/f0e8W#output
Here is the full code as well
<?php
echo "<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>TODO.todo</title></head>
<body>
<style>
.project {
line-height: 4px;
}
.bullet-done {
font-weight: bold;
font-style: normal;
color: rgba(0,114,62,1.0);
}
.note{
display: block;
color: rgba(133,130,102,1.0);
font-weight: normal;
font-style: normal;
}
.todo {
display: inline-block;
}
.tag {
font-weight: bold;
font-style: normal;
color: rgba(160,46,43,0.6);
}
body {
background: rgba(239,233,183,1.0);
color: rgba(0,0,0,0.31);
font-weight: normal;
font-style: normal;
}
h1 {
font-weight: bold;
font-style: normal;
background: rgba(0,0,0,0.06);
color: rgba(188,100,74,1.0);
width: 100%;
line-height: 34px;
}
.tab{
display: inline-block;
width:0px;
height: 0px;
background: #000000;
</style><pre>";
$todo = 'Version 1:
This file is in TaskPaper format.
Tabs are used to indent.
Each task begins with a "- ".
Projects end with a ":".
Tags are in the format "#tag_name".
All other lines (such as these) are considered as notes,
and are to be ignored.
- User signup
- Register for an account
- Log in #done
- Forget password
- Manage users
- Create users #in_progress
- Delete users
- User profile page #40%
- Blog
- Creating new posts #done
- Comments #done
- Moderating comments #done
This is my todo list:
This is a note about the list.
- this is an item #done
- and this is #me
this is a note about my done item
- this is the last #java #shopping #item #done
This is a second list:
- Add more funk to something #work #java
- Send something somewhere #work #email #due(12 Aug 07)
- this is an example
- dfgdfg
ggg
hfghf
- hgh
- dfygdfgdf
List:
- gdfgdf `inline code` hhf
- gdfgdf
- dfgdfg #done
';
echo get_marked_up_todo($todo);
echo '</pre></body></html>';
function get_marked_up_todo($todo){
$todo = htmlspecialchars($todo,ENT_QUOTES)."\n\n";
$search = array('/(.+:)(.+)\n\n/sU', // Get projects
'/(- ([^\#\n]+).+)/', // Get todos
'/(.+:)/', // Get headings
'/\n([^\<\n].+)/', // Get notes
'/- (.+#done)/', // Get done
'/(#due\([^\)]+\))/', // Get due tags
'/(#(?!due)[^\s]+)/', // Get tags
"/\t/",
'/`(.*?)`/', // inline code
);
$replace = array("<div class=\"project\">\n$1$2\n</div>\n\n",
'<span class="todo"><input type="checkbox" value="'.trim('\2').'"> \1</span>',
'<h1>\1</h1>',
"\n\t<span class=\"note\">$1</span>",
'<span class="bullet-done">? ? ??</span> - <strike>\1</strike>',
'<span class="tag due">\1</span>',
'<span class="tag">\1</span>',
"\t<span class=\"tab\"></span>",
'<code>\1</code>',
);
return preg_replace($search, $replace, $todo);
}
If I understood the issue correctly, your issue is that when you use your own replacement for <code>, the <input> tag looks like this:
<input type="checkbox" value="gdfgdf <code>inline code</code> hh">
but you want to it to NOT include the <code>...</code> part, like this:
<input type="checkbox" value="gdfgdf ">.
If my understanding is correct, then you fix you simply need to fix the RegExp that's in charge of rendering the <input> tag, which is this one:
'/(- ([^\#\n]+).+)/', // Get todos
The way it works is by taking everything from - until either a # or a newline (\n) shows up. You want to add do it the backtick:
'/(- ([^\#\n]+).+)/', // Get todos
This will make the RegExp stop capturing when it encounters the first ` and will fix your issue (again, if I understood it correctly).
Writing an extension for a Plugin I have the possibility to change all attributes of an HTML element using PHP.
$attributes["style"] .= 'padding-left:10px;';
array_push($attributes["class"], "long-container");
array_push($attributes["class"], "super smooth");
$attributes["data-whatever"] = "great";
Now I want to give a user the possibility to enter the width / height ratio of a div dynamically (the solution of how to do this is described in the answer by #Web_Designer here: Maintain the aspect ratio of a div with CSS).
Within the function where I can change the output of the third-party Plugin I wrote the following code for calculating the width height ratio according to the input. As the height of my boxes is :
if( !empty( $args['stretchy-desktop'] ) ) {
$sd = array_map('trim',explode(":",$args['stretchy-desktop']));
if(count($sd)==2) {
$sd[0] = floatval(str_replace(",",".",$sd[0]));
$sd[1] = floatval(str_replace(",",".",$sd[1]));
if($sd[0]>0 && $sd[1]>0) {
$padding = ($sd[1] / $sd[0])*100;
array_push($attributes['class'], 'stretchy-desktop');
$attributes['style'] .= 'padding-bottom:'.$padding.'%;';
}
}
}
Great right? However now the user wants a possibility to enter a different weight height ratio for mobile devices as well as a different dynamic min-height for mobile devices and this is there I am stuck.
1) It is not possible to give inline #media queries right now otherwise my solution would be like this (Is it possible to put CSS #media rules inline?):
$attributes['style'] .= '#media (min-width:540px) {padding-bottom:'.$padding.'%;}#media (max-width:539px) {padding-bottom:'.$padding_mobile.';}';
2) It is not possible to use HTML attribute values in CSS right now (CSS values using HTML5 data attribute) otherwise my solution would be like this:
$attributes['data-desktoppadding'] = $padding;
$attributes['data-mobilepadding'] = $padding_mobile;
In CSS:
#media (min-width:540px) {
.long-container {
padding-bottom: attr(data-desktoppadding);
}
}
#media (max-width:539px) {
.long-container {
padding-bottom: attr(data-mobilepadding);
}
}
3) As the values are dynamic numbers I can not define a CSS class for every possible existing float.
Of course I could use JavaScript but we all know the significant drawbacks (including ugly page load).
Can you think of any CSS solution for this dilemma?
Here is a solution I came up with. It involves creating a wrapper div around the target element. Basically, the way that this works is that the outer div is assigned the inline styles for the mobile mode, and the inner div is assigned the inline styles for desktop mode. When the browser window is resized to be below the threshold for desktop view, it resets the inner div's (desktop) inline styles to defaults so the outer div's (mobile) inline styles take over. When the browser window is resized to be above the threshold, it resets the outer div's (mobile) inline styles to defaults so the inner div's (desktop) inline styles take over. The way that it overrides the inline styles is by using the !important keyword in the rulesets in the CSS media queries.
I think it goes without saying that the inline styles in the snippet below would be replaced with your $attributes['style']. But since you will have separate mobile and desktop styles, I guess it would be $attributes['style-mobile'] and $attributes['style-desktop'].
#media (min-width:540px) {
.padding-mobile {
padding-bottom:0 !important;
width: auto !important;
}
}
#media (max-width:539px) {
.padding-desktop {
padding-bottom:0 !important;
width: auto !important;
}
}
<div class="padding-mobile" style="width:100%;background-color:red;padding-bottom:100%;">
<div class="padding-desktop" style="width:50%;background-color:red;padding-bottom:25%;">
</div>
</div>
An elegant approach that works in most major browsers is the usage of custom properties. They are basically variables in CSS. As of writing this (2017-03-27), only IE and Edge do not support this, although they are working on support for Edge.
You would add the variables to the $attributes['style'] and actually apply them in the stylesheet inside a media query. They are then used dynamically by the browser.
I have implemented a demo as a snippet, but because it is easier to change the viewport size on JSFiddle, also a copy of the demo there. Note that the responsive breakpoint is defined in CSS here, and the variables are defined in inline styles of the element.
.container {
width: 200px;
}
.block {
position: relative;
display: block;
box-sizing: border-box;
width: 100%;
height: 0;
padding: 10px;
padding-bottom: var(--desktop-ratio);
background: #bada55;
color: #444;
}
#media (min-width: 540px) {
.mobile {
display: none;
}
}
#media (max-width: 539px) {
.desktop {
display: none;
}
.block {
padding-bottom: var(--mobile-ratio);
}
}
<div class="container">
<div class="block" style="--desktop-ratio: 56.25%; --mobile-ratio: 200%;";>
My aspect ratio is set via custom properties. It is <span class="mobile">1:2</span><span class="desktop">16:9</span>.
</div>
</div>
It is (at least at the moment) apparently not possible to set a breakpoint using a variable. That is,
#media (min-width: var(--breakpoint)) { ... }
is apparently not understood by at least Firefox and Chrome at the moment.
Alternatively, building on Kodos Johnson's answer: if you have only a single breakpoint, you can make use of the padding-bottom and padding-top. One of the two defines the aspect ratio on small screens, and the other defines it on big screens. This removes the need to add a wrapper element. Here is an example, based on the one from Kodos' answer.
#media (min-width:540px) {
.block {
padding-top: 0 !important;
}
}
#media (max-width:539px) {
.block {
padding-bottom: 0 !important;
}
}
<div class="block" style="width: 50%;
padding-bottom: 25%;
padding-top: 100%;
background-color: red;">
</div>
Okay, so I've been able to define the standard text color according to a database value by using this code:
<?php
echo '<div style="color: ' . $result->properties->fcolor . ';';<br />
echo 'background: ' . $result->properties->bgcolor;<br />
echo '">MY CONTENT</div>'
?>
The color that's set by
$results->properties->fcolor
works nicely, except for a:link, a:hover, a:visited, and a:active. Because it's only defining "color", the browsers default to their own link colors.
My users choose from a selection of background and font colors and Chrome's default blue link color doesn't exactly work with a dark purple background... Is it possible to set up a
<style type=text/css>
inside of my PHP file and have it reference the
$result->properties->fcolor
value that the normal part of the script pulls from my database?
This is my first big site so I'm not positive about anything but I vaguely remember enabling PHP in my external CSS file using .htaccess and it didn't successfully pull in the value of
$result->properties->fcolor
as far as I could tell.
What am I doing wrong?
Thanks in advance - amazing community here! :)
IF I'm you, I would create external css for links just to define rules not color.
for example if your links are inside div, what you can do is just define to use color of div
div a { color: inherit; }
div a:HOVER { color: inherit; }
so when you define your color to div through php logic your links inside div will inherit that color.
If you experience any problems with this add important to property so color of div will be used
div a {color: inherit !important; }
YOu can set you link colors via internal css
<style type="text/css">
a:link { color:#f00;}
a:visited { color : }
a:hover {}
a:active { }
</style>
Note:
1 orders are very important .
2 use hex value instead of color name.
Hi have you tried using " instead of ' and \" instead of "?
echo "<div style=\"color: " . $result->properties->fcolor . ";";
echo "background: " . $result->properties->bgcolor;
echo "\">MY CONTENT</div>";
And, you seem to be missing a semi colon at your 3rd echo.