styled div lines disappear for print screen [duplicate] - html

I'm attempting to make a printable stylesheet for our app but I'm having issues with background-color in #media print.
#media print {
#header{display:none;}
#adwrapper{display:none;}
td {
border-bottom: solid;
border-right: solid;
background-color: #c0c0c0;
}
}
Everything else works, I can modify the borders and such but background-color won't come through in the print. Now I understand that y'all might not be able to answer my question without more details. I was just curious if anyone had this issue, or something similar, before.

To enable background printing in Chrome:
body {
-webkit-print-color-adjust: exact !important;
}
Edit:
For Chrome, Safari and Firefox:
body{
-webkit-print-color-adjust:exact !important;
print-color-adjust:exact !important;
}

IF a user has "Print Background colours and images" turned off in their print settings, no CSS will override that, so always account for that. This is a default setting.
Once that is set so it will print background colours and images, what you have there will work.
It is found in different spots.
In IE9beta it's found in Print->Page Options under Paper options
In FireFox it's in Page Setup -> [Format & Options] Tab under Options.

Got it:
CSS:
box-shadow: inset 0 0 0 1000px gold;
Works for all boxes - including table cells !!!
(If the PDF-printer output file is to be believed..?)
Only tested in Chrome + Firefox on Ubuntu...

Try this, it worked for me on Google Chrome:
<style media="print" type="text/css">
.page {
background-color: white !important;
}
</style>

-webkit-print-color-adjust: exact; alone is Not enough
you have to use !important with the attribute
this is printing preview on chrome after I added !important to each background-color and color attrubute in each tag
and this is printing preview on chrome before adding !important
now, to know how to inject !important to div's style, check out this answer I'm unable to inject a style with an “!important” rule

Two solutions that work (on modern Chrome at least - haven't tested beyond):
!important right in the regular css declaration works (not even in the #media print)
Use svg

If you are looking to create "printer friendly" pages, I recommend adding "!important" to your #media print CSS. This encourages most browsers to print your background images, colors, etc.
EXAMPLES:
background:#3F6CAF url('example.png') no-repeat top left !important;
background-color: #3F6CAF !important;

There is another trick you can do without activating the print border option mentioned in other posts. Since borders are printed you can simulate solid background-colors with this hack:
.your-background:before {
content: '';
display: block;
position: absolute;
top: 0;
right: 0;
left: 0;
z-index: -1;
border-bottom: 1000px solid #eee; /* Make it fit your needs */
}
Activate it by adding the class to your element:
<table>
<tr>
<td class="your-background"> </td>
<td class="your-background"> </td>
<td class="your-background"> </td>
</tr>
</table>
Although this needs some extra code and some extra care to make background-colors visible, it is yet the only solution known to me.
Notice this hack won't work on elements other than display: block; or display: table-cell;, so for example <table class="your-background"> and <tr class="your-background"> won't work.
We use this to get background colors in all browsers (still, IE9+ required).

For chrome, I have used something like this and it worked out for me.
Within the body tag,
<body style="-webkit-print-color-adjust: exact;"> </body>
Or for a particular element, let's say if you have table and you want to fill a td i.e a cell,
<table><tr><td style="-webkit-print-color-adjust: exact;"></tr></table>

Despite !important usage being generally frowned upon, this is the offending code in bootstrap.css which prevents table rows from being printed with background-color.
.table td,
.table th {
background-color: #fff !important;
}
Let's assume you are trying to style the following HTML:
<table class="table">
<tr class="highlighted">
<td>Name</td>
<td>School</td>
<td>Height</td>
<td>Weight</td>
</tr>
</table>
To override this CSS, place the following (more specific) rule in your stylesheet:
#media print {
table tr.highlighted > td {
background-color: rgba(247, 202, 24, 0.3) !important;
}
}
This works because the rule is more specific than the bootstrap default.

I just added to the print media query this snippet and all style was applied as intended:
* {
color-adjust: exact!important;
-webkit-print-color-adjust: exact!important;
print-color-adjust: exact!important;
}

Found this issue, because I had a similar problem when trying to generate a PDF from a html output in Google Apps Script where background-colors are also not "printed".
The -webkit-print-color-adjust:exact; and !important solutions of course did not work, but the box-shadow: inset 0 0 0 1000px gold; did... great hack, thank you very much :)

Thought I'd add a recent and 2015 relevant aid from a recent print css experience.
Was able to print backgrounds and colors regardless of print dialog box settings.
To do this, I had to use a combination of !important & -webkit-print-color-adjust:exact !important to get background and colors to print properly.
Also, when declaring colors, I found the most stubborn areas needed a definition directly to your target. For example:
<div class="foo">
<p class="red">Some text</p>
</div>
And your CSS:
.red {color:red !important}
.foo {color:red !important} /* <-- This won't always paint the p */

Tested and Working over Chrome, Firefox, Opera and Edge by 2016/10. Should work on any browser and should always look as expected.
Ok, I did a little cross-browser experiment for printing background colors. Just copy, paste & enjoy!
Here it is a full printable HTML page for bootstrap:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">
/* Both z-index are resolving recursive element containment */
[background-color] {
z-index: 0;
position: relative;
-webkit-print-color-adjust: exact !important;
}
[background-color] canvas {
display: block;
position:absolute;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<!-- CONTENT -->
<body>
<!-- PRINT ROW BLOCK -->
<div class="container">
<div class="row">
<div class="col-xs-6">
<div background-color="#A400C1">
<h4>
Hey... this works !
</h4>
<div background-color="#0068C1">
<p>
Ohh... this works recursive too !!
<div background-color="green" style="width: 80px; height: 60px">
Any size !!
</div>
</p>
</div>
</div>
</div>
<div class="col-xs-6">
<div background-color="#FFCB83" style="height: 200px">
Some content...
</div>
</div>
</div>
<script>
var containers = document.querySelectorAll("[background-color]");
for (i = 0; i < containers.length; i++)
{
// Element
var container = containers[i];
container.insertAdjacentHTML('beforeend', '<canvas id="canvas-' + i + '"></canvas>');
// Color
var color = container.getAttribute("background-color");
container.style.backgroundColor = color;
// Inner Canvas
var canvas = document.getElementById("canvas-" + i);
canvas.width = container.offsetWidth;
canvas.height = container.offsetHeight;
var ctx = canvas.getContext("2d");
ctx.fillStyle = color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
window.print();
</script>
</body>
</html>

Best "solution" I have found is to provide a prominent "Print" button or link which pops up a small dialogue box explaining boldly, briefly and concisely that they need to adjust printer settings (with an ABC 123 bullet point instruction) to enable background and image printing. This has been very successful for me.

In some cases (blocks without any content, but with background) it can be overridden using borders, individually for every block.
For example:
.colored {
background: #000;
border: 1px solid #ccc;
width: 8px;
height: 8px;
}
#media print {
.colored div {
border: 4px solid #000;
width: 0;
height: 0;
}
}

* {
-webkit-print-color-adjust: exact;
}
Also, Enable > Emulate CSS Media From > Inspact > More Tools > Renders. Very detailed steps can be found here.

You can use the tag canvas and "draw" the background, which work on IE9, Gecko and Webkit.

If you don't mind using an image instead of a background color(or possibly an image with your background color) the solution below has worked for me in FireFox,Chrome and even IE without any over-rides. Set the image somewhere on the page and hide it until the user prints.
The html on the page with the background image
<img src="someImage.png" class="background-print-img">
The Css
.background-print-img{
display: none;
}
#media print{
.background-print-img{
background:red;
display: block;
width:100%;
height:100%;
position:absolute;
left:0;
top:0;
z-index:-10;
}
}

Do not set the background-color inside the print stylesheet. Just set the attribute in the normal css file and it works fine :)
Checkout this example: The Ultimate Print HTML Template with Header & Footer
Demo: The Ultimate Print HTML Template with Header & Footer Demo

tr.group-title {
padding-top: .5rem;
border-top: 2rem solid lightgray;
}
tr.group-title > td h5 {
margin-top: -1.9rem;
}
<tbody>
<tr class="group-title">
<td colspan="6">
<h5 align="center">{{ group.title }}</h5>
</td>
</tr>
Works in Chrome and Edge

body{
background-color: #E5FFE5;
}
.bg_print{
border-bottom: 30px solid #FFCC33;
}
.orange_bg_print_content{
margin-top: -25px;
padding: 0 10px;
}
<div class="bg_print">
</div>
<div class="orange_bg_print_content">
My Content With Background!
</div>
Tested and works in Chrome and Firefox and Edge...

Related

#media print not working with background and colors [duplicate]

I'm attempting to make a printable stylesheet for our app but I'm having issues with background-color in #media print.
#media print {
#header{display:none;}
#adwrapper{display:none;}
td {
border-bottom: solid;
border-right: solid;
background-color: #c0c0c0;
}
}
Everything else works, I can modify the borders and such but background-color won't come through in the print. Now I understand that y'all might not be able to answer my question without more details. I was just curious if anyone had this issue, or something similar, before.
To enable background printing in Chrome:
body {
-webkit-print-color-adjust: exact !important;
}
Edit:
For Chrome, Safari and Firefox:
body{
-webkit-print-color-adjust:exact !important;
print-color-adjust:exact !important;
}
IF a user has "Print Background colours and images" turned off in their print settings, no CSS will override that, so always account for that. This is a default setting.
Once that is set so it will print background colours and images, what you have there will work.
It is found in different spots.
In IE9beta it's found in Print->Page Options under Paper options
In FireFox it's in Page Setup -> [Format & Options] Tab under Options.
Got it:
CSS:
box-shadow: inset 0 0 0 1000px gold;
Works for all boxes - including table cells !!!
(If the PDF-printer output file is to be believed..?)
Only tested in Chrome + Firefox on Ubuntu...
Try this, it worked for me on Google Chrome:
<style media="print" type="text/css">
.page {
background-color: white !important;
}
</style>
-webkit-print-color-adjust: exact; alone is Not enough
you have to use !important with the attribute
this is printing preview on chrome after I added !important to each background-color and color attrubute in each tag
and this is printing preview on chrome before adding !important
now, to know how to inject !important to div's style, check out this answer I'm unable to inject a style with an “!important” rule
Two solutions that work (on modern Chrome at least - haven't tested beyond):
!important right in the regular css declaration works (not even in the #media print)
Use svg
If you are looking to create "printer friendly" pages, I recommend adding "!important" to your #media print CSS. This encourages most browsers to print your background images, colors, etc.
EXAMPLES:
background:#3F6CAF url('example.png') no-repeat top left !important;
background-color: #3F6CAF !important;
There is another trick you can do without activating the print border option mentioned in other posts. Since borders are printed you can simulate solid background-colors with this hack:
.your-background:before {
content: '';
display: block;
position: absolute;
top: 0;
right: 0;
left: 0;
z-index: -1;
border-bottom: 1000px solid #eee; /* Make it fit your needs */
}
Activate it by adding the class to your element:
<table>
<tr>
<td class="your-background"> </td>
<td class="your-background"> </td>
<td class="your-background"> </td>
</tr>
</table>
Although this needs some extra code and some extra care to make background-colors visible, it is yet the only solution known to me.
Notice this hack won't work on elements other than display: block; or display: table-cell;, so for example <table class="your-background"> and <tr class="your-background"> won't work.
We use this to get background colors in all browsers (still, IE9+ required).
For chrome, I have used something like this and it worked out for me.
Within the body tag,
<body style="-webkit-print-color-adjust: exact;"> </body>
Or for a particular element, let's say if you have table and you want to fill a td i.e a cell,
<table><tr><td style="-webkit-print-color-adjust: exact;"></tr></table>
Despite !important usage being generally frowned upon, this is the offending code in bootstrap.css which prevents table rows from being printed with background-color.
.table td,
.table th {
background-color: #fff !important;
}
Let's assume you are trying to style the following HTML:
<table class="table">
<tr class="highlighted">
<td>Name</td>
<td>School</td>
<td>Height</td>
<td>Weight</td>
</tr>
</table>
To override this CSS, place the following (more specific) rule in your stylesheet:
#media print {
table tr.highlighted > td {
background-color: rgba(247, 202, 24, 0.3) !important;
}
}
This works because the rule is more specific than the bootstrap default.
I just added to the print media query this snippet and all style was applied as intended:
* {
color-adjust: exact!important;
-webkit-print-color-adjust: exact!important;
print-color-adjust: exact!important;
}
Found this issue, because I had a similar problem when trying to generate a PDF from a html output in Google Apps Script where background-colors are also not "printed".
The -webkit-print-color-adjust:exact; and !important solutions of course did not work, but the box-shadow: inset 0 0 0 1000px gold; did... great hack, thank you very much :)
Thought I'd add a recent and 2015 relevant aid from a recent print css experience.
Was able to print backgrounds and colors regardless of print dialog box settings.
To do this, I had to use a combination of !important & -webkit-print-color-adjust:exact !important to get background and colors to print properly.
Also, when declaring colors, I found the most stubborn areas needed a definition directly to your target. For example:
<div class="foo">
<p class="red">Some text</p>
</div>
And your CSS:
.red {color:red !important}
.foo {color:red !important} /* <-- This won't always paint the p */
Tested and Working over Chrome, Firefox, Opera and Edge by 2016/10. Should work on any browser and should always look as expected.
Ok, I did a little cross-browser experiment for printing background colors. Just copy, paste & enjoy!
Here it is a full printable HTML page for bootstrap:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">
/* Both z-index are resolving recursive element containment */
[background-color] {
z-index: 0;
position: relative;
-webkit-print-color-adjust: exact !important;
}
[background-color] canvas {
display: block;
position:absolute;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<!-- CONTENT -->
<body>
<!-- PRINT ROW BLOCK -->
<div class="container">
<div class="row">
<div class="col-xs-6">
<div background-color="#A400C1">
<h4>
Hey... this works !
</h4>
<div background-color="#0068C1">
<p>
Ohh... this works recursive too !!
<div background-color="green" style="width: 80px; height: 60px">
Any size !!
</div>
</p>
</div>
</div>
</div>
<div class="col-xs-6">
<div background-color="#FFCB83" style="height: 200px">
Some content...
</div>
</div>
</div>
<script>
var containers = document.querySelectorAll("[background-color]");
for (i = 0; i < containers.length; i++)
{
// Element
var container = containers[i];
container.insertAdjacentHTML('beforeend', '<canvas id="canvas-' + i + '"></canvas>');
// Color
var color = container.getAttribute("background-color");
container.style.backgroundColor = color;
// Inner Canvas
var canvas = document.getElementById("canvas-" + i);
canvas.width = container.offsetWidth;
canvas.height = container.offsetHeight;
var ctx = canvas.getContext("2d");
ctx.fillStyle = color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
window.print();
</script>
</body>
</html>
Best "solution" I have found is to provide a prominent "Print" button or link which pops up a small dialogue box explaining boldly, briefly and concisely that they need to adjust printer settings (with an ABC 123 bullet point instruction) to enable background and image printing. This has been very successful for me.
In some cases (blocks without any content, but with background) it can be overridden using borders, individually for every block.
For example:
.colored {
background: #000;
border: 1px solid #ccc;
width: 8px;
height: 8px;
}
#media print {
.colored div {
border: 4px solid #000;
width: 0;
height: 0;
}
}
* {
-webkit-print-color-adjust: exact;
}
Also, Enable > Emulate CSS Media From > Inspact > More Tools > Renders. Very detailed steps can be found here.
You can use the tag canvas and "draw" the background, which work on IE9, Gecko and Webkit.
If you don't mind using an image instead of a background color(or possibly an image with your background color) the solution below has worked for me in FireFox,Chrome and even IE without any over-rides. Set the image somewhere on the page and hide it until the user prints.
The html on the page with the background image
<img src="someImage.png" class="background-print-img">
The Css
.background-print-img{
display: none;
}
#media print{
.background-print-img{
background:red;
display: block;
width:100%;
height:100%;
position:absolute;
left:0;
top:0;
z-index:-10;
}
}
Do not set the background-color inside the print stylesheet. Just set the attribute in the normal css file and it works fine :)
Checkout this example: The Ultimate Print HTML Template with Header & Footer
Demo: The Ultimate Print HTML Template with Header & Footer Demo
tr.group-title {
padding-top: .5rem;
border-top: 2rem solid lightgray;
}
tr.group-title > td h5 {
margin-top: -1.9rem;
}
<tbody>
<tr class="group-title">
<td colspan="6">
<h5 align="center">{{ group.title }}</h5>
</td>
</tr>
Works in Chrome and Edge
body{
background-color: #E5FFE5;
}
.bg_print{
border-bottom: 30px solid #FFCC33;
}
.orange_bg_print_content{
margin-top: -25px;
padding: 0 10px;
}
<div class="bg_print">
</div>
<div class="orange_bg_print_content">
My Content With Background!
</div>
Tested and works in Chrome and Firefox and Edge...

Background color not showing in print preview

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.
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!
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
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" />

Difference in displaying inner div between IE and Chrome

I have this code that has one "outerDIV" that contains an "innerDIV". On chrome the "innerDIV" size is 491px, whereas on IE it is 425px (same as outerDIV). Hence, on Chrome I can see the first two children of "innerdiv": "My test string #1" and "test2". But for IE I can only see the first child.
I am not quite sure what the "right" behavior should be, as firefox does the same as IE. However I would like to have IE do the same as Chrome.
I have been experimenting with some css styles (mainly overflow and display), but still can't make it right: IE will expand its height instead of its width to make the elements fit.
Can you guys help me figure out a way to change the css so that IE will wraps the div elements inline? As a restriction though, I cannot change the width on the HTML. As a benefit, I am using a css that only loads for IE to patch these kind of IE inconsistencies. The same css will NOT load for chrome, so I don't need to worry about messing with chrome when changing the IE CSS. Thanks in advance!
<html>
<head>
<style type="text/css">
<!--
body {
font-family: helvetica;
}
.myContainer {
overflow: hidden;
border: 1px solid rgba(0, 0, 0, .5);
font-size: 14pt;
height: 49px;
line-height: 49px;
overflow: hidden;
display: block;
}
.myContainer > DIV {
float: left;
white-space: nowrap;
display: block;
}
.myContainer .item:first-child {
padding-left: 10px;
}
.myContainer .item {
float: left;
padding-right: 32px;
}
-->
</style>
</head>
<body>
<div id="outerDIV" class="myContainer" style="display: block; width: 425px;">
<div id="innerDIV">
<div class="item">
--------My test string #1--------
</div>
<div class="item">
------test2-------
</div>
<div class="item">
test
</div>
</div>
</div>
</body>
</html>
You need a doctype tag on your page, otherwise it will be rendered in quirks mode.
What that means exactly differs from browser to browser, but basically it tries to be compatible with very old browsers. In IE it triggers the non-standard box model, which would explain the differences in size.
Look at the W3C recommended list of doctype declarations for a doctype tag to use.
set the width of .item ... container overflow: hidden hides the items which are shown verticaly because the width is more than a 'line' of container can show. When using floating is good to have the width set. DOCTYPE is very important to be set too. I personaly use loose.dtd which gives good competability.
I could not solve it purely with css. For IE, seems like the only way to fix this is to have the "innerDIV" element to have a width >= the sum of it's children offsetWidth. So I just added this to my JS code (special case for IE):
var len = innerDiv.childNodes.length,
innerDivWidth = 0,
i;
for(i = 0; i < len; i++){
innerDiv += innerDiv.childNodes[i].offsetWidth;
}
innerDiv.style.width = (innerDiv + 1) + 'px'; //Safety measure to make up for the decimal places. I guess we could write this line in a better way by rounding up, etc.

css - how to change image source by its id?

Does anyone know how can I control the image source from the CSS?
I need to be able to change the image src from the CSS. I have loop printing < img id=.. > tags, and for every id it different image. I want to be able to set the source by its id from the style css area.
Does anyone know how to do this?
This is not possible: The image's source is part of the markup, not CSS.
The only workaround would be having div elements with background-image properties instead. Those you could set from within the style sheet:
<div id="image1"></div>
#image1 { width: 100px; height: 50px; background-image: url(image.gif); }
However, with this method you lose all the img tag's advantages like
The ability to set an alt text
Resizing
Printing (most browsers don't print background images)
Search engine indexing (probably)
the only other alternative is by using JavaScript, but that obviously won't work if JavaScript is disabled, which makes it a no-no in my view.
This is now possible with CSS3 using the Content style.
I use this to swap images within a slider based on window size through media queries.
Edit: When I originally posted this, I was unaware that it only worked in Webkit at the moment. But I doubt it will take long before it gains more functionality across browsers.
HTML
<img class="img1" src="image.jpg">
CSS
#media (min-width: 768px) {
.img1 {
content: url(image.jpg);
}
}
#media (max-width: 767px){
.img1 {
content: url(new-image.jpg);
}
}
That is not possible with CSS.
However, this is very easy with Javascript:
document.getElementById("IdOfImage").src = "SourceOfImage";
You cannot really do that, however, if you do need to do that using CSS, you can do it for two images with the same size like this:
<style>
img {
width:0;
height:0;
display:block;
background: url('2.png') no-repeat bottom left;
padding-left:196px;
padding-bottom:187px;
}
</style>
<img src="1.png">
Only tested it in FF3.6 though.
I found this article that might be useful. It actually changes background of an image
here is the example in case website goes missing:
HTML
<html>
<body>
<div class="header">
<img class="banner" src="http://notrealdomain1.com/banner.png">
</div>
</body>
</html>
CSS
/* All in one selector */
.banner {
display: block;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: url(http://notrealdomain2.com/newbanner.png) no-repeat;
width: 180px; /* Width of new image */
height: 236px; /* Height of new image */
padding-left: 180px; /* Equal to width of new image */
}
If you don't want to use backgrounds nor use javascript, you layer 2 images with different src on top of each other (using absolute positioning) and use CSS to hide one or another. Visually it will be the same then changing the src.

How can I print background images in FF or IE?

Is there any way to set ff and ie to print background images?
I am using stars image to classify some skills and I set it as a background image and positioning to either set one start, two, three, etc. When I try to print the page the images disappear.
So is there any way to make them appear when I print the page or at least have a way of replacing the images with * or something that would be visible?
Have you considered using a print stylesheet? This could allow you to do something like:
<div class="star">*</div>
/* media:screen */
.star {
background: ...;
overflow: hidden;
text-indent: 9999em;
}
/* media:print */
.star {
text-indent: 0;
}
or even easier:
<div class="star"><img src="./images/star.jpg" alt="*" /></div>
/* media:screen */
.star img {
visibility: hidden;
}
/* media:print */
.star img {
visibility: visible;
}
You can specify stylesheets browsers should use by supplying a media tag, either by css or on the link element:
<link rel="stylesheet" type="text/css" href="main.css" media="screen" />
<link rel="print stylesheet" type="text/css" href="print.css" media="print" />
In Firefox, go to File => Page Setup. There is a checkbox for "Print Background (colors & images)". Just check that and you should be all set.
In your print.css file change the background-image to a list item.
So:
.background {
display: list-item;
list-style-image: url(yourbackgroundimage.gif);
list-style-position: inside;
}
This method is described more here: http://www.web-graphics.com/mtarchive/001703.php
Actually I found the answer to be rather simple.
Situation: I had a div tag with a background image. Which would not printout when printing.
Solution:
Create another style sheet called "print.css"
Add the following line of code to your all your web pages right after your orginal css stylesheet link:
<link rel="stylesheet" type="text/css" media="print" href="css/print_styles.css" />
Immediately after your for the original non printing header, add the following:
<div id="header"></div> <!-- YOUR NON PRINTING HEADER -->
<div id="printheader"><img src="images/header_image.jpg" width="940" height="100" alt="header" /></div>
In your style.css file, which is the main css style for you site, add the following line:
#printheader {display: none; } /* Makes the print header not visible */
In your print.css file, add the following code:
#footer, #nav, #sidenav, .print, .search, .breadcrumb, .noprint {display: none;} /* Items from your page you DO NOT want to print */
#container, #container2, #contentwide, #contentwide_tpsub, #contentwide_tp, #contentwide_open {width: 100%; margin: 0; float: none;} /* Clear widths to ensure all text is printed */
#printheader {display: block; } /* Turns ON the div when printing */
What you are doing is essentially turning OFF the header on the normal "screen" page and turning the printheader ON when you make a print call.
** Please note: you will need to modify the print.css file to include other elements of your style.css file to format the fonts, colors, etc. Play around with "Print Preview" and add in the elements you need till you get the printout that you've been seeking.
Don't use background-image to display printable images, use the normal <img> tag instead.
background-image is meant for unimportant images which most modern browsers tend to skip during printing (default setting in IE 11, Chrome 35, FF 30).
Why would you not want to use the img tag?
Alignment issues - Use absolute positioning to solve alignment issues.
Spriting - Spriting is possible using simple img and div tags.
Make it more difficult for users to save the image - That is also possible with simple img and div tags.
To "keep my HTML clean" - do any of the workaround solutions really make it cleaner for you? Give it up :)
For IE http://support.microsoft.com/kb/980077
There must be something similar for FF.
p.s. you cannot set this for clients!
p.s.2. you can replace this stars with foreground pictures (absolute if needed) in css (media="print").
I had the same issue with IE not supporting the printing the background.
So I created 2 divs, one div had a higher Z and had the text content. The second div was immediately behind the front div but a lower Z index and had a image (img not background image) for width and height of 100%. So when I showed the 2 divs together it looked like one div because they perfectly overlapped. When I printed in IE Browser it shows with image because the image is not a background image but a normal img tag that fills a lower div.
some code.
<div id="survey" class="surveyResponseWindow" style="display:none;">Please logout and re-login, because your session has expired.</div>
<div id="surveyBackground" class="surveyBackgroundDiv" style="display:none;">
<!-- provides the background image for ie browser so that it does not show the lower level divs. -->
<img src="/rsm/jsp/public/images/contentGrad.gif" width="100%" height="100%" />
</div>
<script language="javascript" type="text/javascript">
function showSurvey(surveyResponseId) {
var e = document.getElementById("survey");
var bkgd = document.getElementById("surveyBackground");
var focusinput = document.getElementById('focusinput');
var nh = 'data-nohide';
if (e.style.display=='none') {
e.style.display='block';//show div
bkgd.style.display='block';//show div
}
focusinput.focus();//set focus so we know when they click outside
e.onclick = function(e) {
this.style.display='none';//hide div if they click on it
bkgd.style.display='none';//show div
};
//if the user press ESC
focusinput.onkeyup = function(e){
if(e.keyCode === 27){
var survey = document.getElementById("survey");
var bkgd = document.getElementById("surveyBackground");
//hide the div
survey.style.display = 'none';
bkgd.style.display = 'none';
this.removeAttribute(nh);
}else{
//do something else with other keys(ie:down, up, enter)...
focusinput.focus();
}
};
//click somewhere else input onblur
// was taken out because the browser print function would close the survey div page.
//focusinput.onblur = function(){
// if(!e.getAttribute(nh)){
// //hide the div
// e.style.display = 'none';
// }
//};
var params='<%=request.getContextPath()%>/request/dashboard/drilldown/callSurveyDetailAjax.html?surveyResponseId='+surveyResponseId;
YAHOO.plugin.Dispatcher.fetch(e,params, {onLoad:showBackground});
}
var showBackground = function() {
var e = document.getElementById("survey");
var bkgd = document.getElementById("surveyBackground");
bkgd.style.width = e.innerWidth();
bkgd.style.height = e.innerHeight();
bkgd.style.left = e.offsetWidth();
bkgd.style.top = e.offsetHeight();
}
window.onload = function() {
var focusinput = document.getElementById('focusinput');
focusinput.focus();//set focus so we know when they click outside
}
</script>
in CSS put this
.surveyResponseWindow
{
width:500px;
height:600px;
z-index: 2;
position: absolute;
top:100px;
left:150px;
border:1px solid #AAAAAA;
border-bottom-left-radius:10px;
border-bottom-right-radius:10px;
border-top-left-radius:10px;
border-top-right-radius:10px;
box-shadow: -1px 7px 15px -2px #000;
}
.surveyBackgroundDiv
{
z-index: 1;
position: absolute;
top:100px;
left:150px;
width:500px;
height:600px;
border:1px solid #AAAAAA;
border-bottom-left-radius:10px;
border-bottom-right-radius:10px;
border-top-left-radius:10px;
border-top-right-radius:10px;
box-shadow: -1px 7px 15px -2px #000;
}
I believe this is a browser setting, not the backend of the web sites. I could be wrong however.