CSS #media print rule does not work anymore? - html

Previously, the following code works fine for both Firefox and Google Chrome when I print to "hide" the element,
<!DOCTYPE html>
<html><head><title>Test</title>
<style type="text/css">
#media print {
.noprint {
display: none;
}
}
</style>
</head>
<body>
<span class="noprint">abc</span>
</body></html>
But now, it does not work for both browsers. However, if I change to this,
<!DOCTYPE html>
<html><head><title>Test</title>
<style type="text/css" media="print">
.noprint {
display: none;
}
</style>
</head>
<body>
<span class="noprint">abc</span>
</body></html>
It will work on Firefox, but not on Google Chrome.
What is the solution which works as browser independent?
(Or is there something wrong with my code?)

If you are using #media print, you need to add !important in your styles, or the page will use the elements inline styles.
E.g.
#media print {
.myelement1, .myelement2 { display: none !important; }
}

Not sure what is the problem with the Google Chrome, but today I tested again with Google Chrome version 31.0.1650, the solution with < style media="print" > works well.
And "#media print" rule is still not working.

"#media print" & < style media="print" > both working fine on Chrome 39.0.2171.95 (64-bit) Mac-OS & Firefox 34.0.5 Mac-OS

It sounds to me like you have a style rule in your non-print sheet cascading over your print sheet rule. You are using a form of "internal" or embedded styling (not inline or external) that has higher selectivity in the cascade order over external styles but not inline. A true inline style in your HTML or in a screen style sheet with higher selectivity in your styles could be cascading over it.
Additionally: In the case of external linked style sheets, that concept will not work for many modern browsers using a linked style sheet with #media print styles inside if the style sheet has its media attribute value set to anything other than print.....UNLESS all the other non-print styles are inside a matching #media screen{...} rule in that sheet and you remove the "media=screen" attribute from the linked style sheet entirely (defaults to media=all). This may be what is happening in your internal print style example as the browser may assume your other styles are for both screen and print (all).
Many browsers currently will not support that type of mixed media query rule as they don't know what device your sheet and styles combined are designed for and mixing styles like this with without specific media attributes just confuses the parsers. If an external linked parent style sheet says it is set to "screen", it assumes all styles in there are for screen and vice versa. An so it would fail in allowing any print styles to be defined inside. Use of inline styles on elements is even worse as far as defining media type as they would apply to all media types by default.
Older browsers at one time supported a variety of combined media settings like this, but the consensus now is to use external linked sheets for print as it's cross-browser compatible going back to older browsers pre-2001.
BEST PRACTICES FOR PRINT IN CSS
The best way to do print style is to place them in linked sheets specifically set for screen and print as shown below...
<link media="screen" rel="stylesheet" type="text/css" href="..." />
<link media="print" rel="stylesheet" type="text/css" href="..." />
In that print sheet you don't need the #media print query any longer as everything in the style sheet with "media=print" will only be seen by printers. But if you do, it also should work ok. It would just be redundant.
There also is another option using the format #import 'print.css' print;. But I don't recommend that as a large number of browsers do not support the media type in #import, including Internet Explorer 1-7 and many others which would ignore this rule and not import the sheet.
You do NOT need !important in any of those rules, EXCEPT if you used !important in your regular style sheets. Those styles would override print sheet values, too. To cascade over those selectors, you would need a more selective copy of that selector or class in your print sheet with the !important value set to properties that match those in your screen sheet's style class.
This is yet another reason to not use !important in style sheets unless absolutely necessary.

"#media print" & < style media="print" > not working Version 76.0.3809.100 (Official Build). only style media="print"

Related

Media Query in External CSS File

I am modifying my CSS3/HTML5 site to work with different Medial Queries.
The site pages are in the Root directory. The CSS files are within a folder in the root directory called css.
Within the HEAD tags of my page, I have one CSS file for the default stuff and then I have another one for iPad in an external CSS file called ipad.css
When I am in the Developer Tools within Google Chrome, it doesn't seem to be applying the rules within the ipad.css file. I know this because I am wanting to change the text size of an element and it is not changing. Nothing is happening.
This is what I have within the HEAD tags:
<link rel="stylesheet" type="text/css" href="css/default.css" title="Default Styles">
<link rel="stylesheet" type="text/css" href="css/ipad.css" media="screen and (max-device-width: 768px)" title="iPad Styles">
According to the Google Chrome Developer Tools, an iPad width is 768px. I have referenced this within the link tag. Any ideas or suggestions welcome.
Use max-width: 768px rather than max-device-width: 768px.
Also, remember to specify a viewport meta tag in the head section of your html.
<meta name="viewport" content="width=device-width, initial-scale=1" />
Also, you might want to check
What is the difference between max-device-width and max-width for mobile web?
Also, keep in my you're not targeting devices, you're targeting resolutions.
Another possible source of your problem might be that you are using less specific selectors in your ipad.css. Don't forget that the styles from your default.css are also used on resolutions lower than 769px!
To test this, put this css rule on the very top of your ipad.css:
* { display: none !important; }
If your site vanishes then, your stylesheet is loaded and applied.
I tried the max-width as well and the style isn't applying. Even if I change the font-color of the text within the div class (p tag), nothing is happening.
As an example, I have a div class called banner-textoverlay so, in my ipad.css file, I wrote the following to see if it would change the text color and nothing happens at all.
.banner-textoverlay p {
font-color:#000000;
}

Print media queries being ignored in Chrome?

I'm creating some print specific styles using the following:
#media print {
/* Styles */
}
As we are using SASS all the styles get compiled into one stylesheet, styles.css at runtime, which is declared in the <head> of the document as follows:
<link rel='stylesheet' href='/assets/css/styles.css'>
Now when I print from chrome (Ctrl+P), it completely ignores my print styles but Firefox (30.0) is fine. IE(11) is terrible but this is because we have a lot of show/hide panels which IE doesn't seem to like/
Can't for the life of me figure out what's happening. If I emulate print media in Chrome then it loads the styles fine, it's when I actually try and print that it doesn't work. I've tried loads of things, adding, media= attributes, double quotes, changing the order of href etc all to no avail!!
Note, we're not using type anymore as I thought you didn't need to use this anymore. I've tried adding this anyway but it still doesn't work!
I've even tried this: http://lawrencenaman.com/optimisation/print-media-queries-not-working/ but it still doesn't work. It's driving me crazy, any ideas?
UPDATE: So I noticed that when I hit Ctrl + P to print the page, the preview that I see seems to use some of the styles from the print stylesheet but seems to render everything using a mobile media query? I think there may be some conflict with a breakpoint, will update when I get a chance.
UPDATE2: I can see that the print stylesheet is loading at the bottom so this should in theory over write all the other media queries (at least the ones that I'm trying to over write)?
I tried to add
#media print {
* {
display:none;
}
}
to one of my sites' style.css: Doesn't work.
Then I added
<link rel="stylesheet" href="/css/print.css" media="print">
after the other stylesheets into the head and inserted the same rule as above (without #media print {}) to the print.css. Chrome now interprets the rule and does not display anything within the print preview.
I'd assume the problem is using #media print. But I have no idea why chrome behaves like that.
EDIT:
Other Solution via JavaScript:
if(/chrome/i.test(navigator.userAgent) {
document.write('<link rel="stylesheet" href="printChrome.css" media="print">');
}
You can try setting rest of the stylesheets media attribute as
media="screen" and print stylesheet to media="print".
This will prevent browser from applying rules from stylesheets marked as "screen".
Worked for me
I ran into this problem as well and found that it was because of my rendering settings in Chrome. When testing the print preview I had set my emulation media type to be "print". When I went to actually test printing, I set my media emulation to be "screen". I should have set it to be "no emulation". When it was on "screen" the print preview ignored all the print media queries and still treated the page like it was a screen. When I finally set it back to "no emulation" it started behaving as you would expect.
A problem I had was that rel='stylesheet' wasn't set in the print css link. Adding it fixed the problem.
Another way to make this happen: CSS errors ahead of the print styles. Since we all seem to have the impulse to put print styles last they're more vulnerable to this. When CSS has an error it doesn't complain... it just throws away the rest of the stylesheet.
Giving the print styles their own stylesheet--even merely a separate inline tag--can solve this as well as the media-spec'd-in-style-tag error.

CSS Style for my Bootstrap are being overridden by User Agent Stylesheet [duplicate]

I'm working on a web page in Google Chrome. It displays correctly with the following styles.
table {
display: table;
border-collapse: separate;
border-spacing: 2px;
border-color: gray;
}
It is important to note that I didn't define these styles. In Chrome developer tools, it says user agent stylesheet in place of the CSS file name.
Now if I submit a form and some validation error occurs, I get the following stylesheet:
table {
white-space: normal;
line-height: normal;
font-weight: normal;
font-size: medium;
font-variant: normal;
font-style: normal;
color: -webkit-text;
text-align: -webkit-auto;
}
table {
display: table;
border-collapse: separate;
border-spacing: 2px;
border-color: gray;
}
The font-size from these new styles is disturbing my design. Is there a way to force my stylesheets and if possible, completely overwrite Chrome's default stylesheet?
What are the target browsers? Different browsers set different default CSS rules. Try including a CSS reset, such as the meyerweb CSS reset or normalize.css, to remove those defaults. Google "CSS reset vs normalize" to see the differences.
If <!DOCTYPE> is missing in your HTML content you may experience that the browser gives preference to the "user agent stylesheet" over your custom stylesheet. Adding the doctype fixes this.
Regarding the concept “user agent style sheet”, consult section Cascade in the CSS 2.1 spec.
User agent style sheets are overridden by anything that you set in your own style sheet. They are just the rock bottom: in the absence of any style sheets provided by the page or by the user, the browser still has to render the content somehow, and the user agent style sheet just describes this.
So if you think you have a problem with a user agent style sheet, then you really have a problem with your markup, or your style sheet, or both (about which you wrote nothing).
Marking the document as HTML5 by the proper doctype on the first line, solved my issue.
<!DOCTYPE html>
<html>...
A user agent style sheet is a ”default style sheet” provided by the browser (e.g., Chrome, Firefox, Edge, etc.) in order to present the page in a way that satisfies ”general presentation expectations.” For example, a default style sheet would provide base styles for things like font size, borders, and spacing between elements.
It is also common to use a CSS Reset to normalize or remove inconsistencies between browsers due to differences between which base styles are applied by each browser.
From the specification...
A user agent's default style sheet should present the elements of the document language in ways that satisfy general presentation expectations for the document language. ~ The Cascade.
For more information about user agents in general, see user agent.
Answering the question in title, what is the user agent stylesheet, the set of default styles in the browser: Here are some of them:
Chromium (Chrome): https://chromium.googlesource.com/chromium/src/third_party/+/master/blink/renderer/core/html/resources/html.css
WebKit (Safari): https://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css
Gecko (Firefox): https://searchfox.org/mozilla-central/source/layout/style/res/html.css
Serenity: https://github.com/SerenityOS/serenity/blob/master/Userland/Libraries/LibWeb/CSS/Default.css#L4
Mozilla Servo: https://github.com/servo/servo/blob/master/resources/user-agent.css#L9
Personal opinion: Don't fight with them. They have good default values, for example, in rtl/bidi cases and are consistent nowadays. Reset what you see irrelevant to you, not all of them at once.
Define the values that you don't want to be used from Chrome's user agent style in your own CSS content.
Some browsers use their own way to read .css files.
So the right way to beat this:
If you type the command line directly in the .html source code, this beats the .css file, in that way, you told the browser directly what to do and the browser is at position not to read the commands from the .css file.
Remember that the commands writen in the .html file is stronger than the command in the .css.
I had the same problem as one of my <div>'s had the margin set by the browser. It was quite annoying but then I figured out as most of the people said, it's a markup error.
I went back and checked my <head> section and my CSS link was like below:
<link rel="stylesheet" href="ex.css">
I included type in it and made it like below:
<link rel="stylesheet" type="text/css" href="ex.css">
My problem was solved.
I just wanted to expand on the response from #BenM based on what I read here from Ire Aderinokun. Because the user-agent stylesheet provides helpful default styling, think twice before overriding it.
I had a dumb error where a button element didn't look right in Chrome. I had partially styled it because I didn't want it to look like a traditional button. However, I left out style elements like border, border-color, etc. So Chrome was stepping in to supply the parts that it thought I was missing.
The problem went away once I added styles like border: none, etc.
So if anyone else is having this problem, make sure you are explicitly overriding all the applicable default user-agent styles for an element if you notice it looks wonky, especially if you don't want to reset the user agent styles completely. It worked for me.
Each browser provides a default stylesheet, called the user agent stylesheet, in case an HTML file does not specify one. Styles that you specify override the defaults.
Because you have not specified values for the table element’s box, the default styles have been applied.
I ran into this same issue, it was because I was working with non-semantic html
<!--incorrect-->
<ul class="my-custom-font">
<button>
<a>user agent styles applied instead of my-custom-font</a>
<button>
</ul>
<!--correct-->
<ul class="my-custom-font">
<li>
<a>now inherits from from my-custom-font</a>
</li>
</ul>
Once the HTML was updated, styles were applied correctly
Every browser will have a rendering engine responsible for converting HTML document to web page.
The rendering engine will have a stylesheet of its own for all the HTML elements, a kind of default stylesheet for all the HTML elements and this stylesheet is called user agent stylesheet.
The rules of user agent stylesheet can be overwritten by author stylesheet.
The rendering engine for google chrome browser is called 𝐛𝐥𝐢𝐧𝐤. And if you look through its source code you will be able to find the default stylesheet.
check this https://www.linkedin.com/posts/smruti-sagar-pattanaik-a3a000195_html-css-chrome-activity-7027888128115847168-USil?utm_source=share&utm_medium=member_desktop
I have a solution. Check this:
Error
<link href="assets/css/bootstrap.min.css" rel="text/css" type="stylesheet">
Correct
<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
Put the following code in your CSS file:
table {
font-size: inherit;
}

Browser controlled text for print stylesheet

Is there an easy way to overwrite all text/header styles to let the browser handle the text formatting in the print stylesheet?
Edit:
I have lots of styles such as
#id .class .class #id .class p{}
Make sure that any styles you have applied to the text / header which you do not want applied during "print" mode are specified as;
#media screen {
.headerStyle { color: green; }
}
They will then be ignored during the #print screen mode.
No. You can only cascade downwards, and you can't refer to other styles. Limit the CSS you have to the media types you want in the first place.
I have learnt that any CSS formatting created in a stylesheet specified as screen does means that the printing page will be unformatted.
In my example, I can't touch the HTML and the CSS media has not been specified, so the problem remains, but you should always make sure you set this to avoid problems in other medias.
Set the CSS globally (including print)
<link href="style.css" rel="stylesheet" type="text/css">
Set the CSS just for screen (excludes any media, including print format)
<link href="style.css" rel="stylesheet" type="text/css" media="screen">

How can you make a web page send to the printer something different than what's in the browser window?

Google Maps used to do this bit where when you hit the "Print" link, what would be sent to the printer wasn't exactly what you had on the screen, but rather a differently-formatted version of mostly the same information.
It appears that they've largely moved away from this concept (I guess people didn't understand it) and most websites have a "print version" of things like articles and so forth.
But if you wanted to make a webpage such that a "printer friendly" version of the page is what gets sent to the printer without having to make a separate page for it, how would you do that?
You can achieve this effect by creating a css stylesheet which is targeted directly to printing, and another targeted directly for the screen.
Use the link tag:
<link rel="stylesheet" type="text/css" href="print.css" media="print, handheld" />
<link rel="stylesheet" type="text/css" href="screen.css" media="screen" />
to embed your stylesheet into your document.
To hide is easy, just set your block style to hidden in whatever stylesheet you want and it wont be displayed. For example:
.newStyle1 {
display: none;
}
Then anything set to the style of newStyle1 will not be displayed.
The #media rule in CSS can be used to define alternate rules for print.This is often used to hide navigation and change the style to fit print better:
#media print {
.sidebar { display: none; }
}
You can also link a seperate stylesheet for print:
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
You can do this with the css when you specify media as print.
Another way, if desired, is to have the 'print' button on the page change the page in some way that you decide, then perform a javascript 'window.print();' to bring up the browser's print dialog.
There are several options available to you:
You can open a new window with slightly different data to be printed.
There are also CSS styles which you can use to alter the page layout.
Finally you can specify completly different style sheets for screen, printed media, Braille readers etc.
e.g. <link href="css/print.css" type="text/css" rel="stylesheet" media="print" />
See also CSS2 Print Reference
Use a print stylesheet.
Edit: Regarding the followup, you can't, in general, add things to a page with CSS.
One option is to include your print-only content in the page, and hide it for screen stylesheets. You should make sure that the page still makes sense without CSS though.
Another option is to use generated content, but this isn't supported by Internet Explorer 7 and below, and can be quite limited.
If the print-only content is an image, you can swap that out using one of the popular image replacement techniques.
The easiest way is to use CSS media types. For each CSS file you include, you can specify where it ought to be used: on-screen, when printing, for handhelds, for screen-readers, or various combinations of these.
Example: <link rel="stylesheet" type="text/css" media="print, handheld" href="foo.css">
This has been a standard since CSS2, and most browsers support it now. More information is available here: http://www.w3.org/TR/CSS2/media.html
CSS allows you to create stylesheets for particular types of media, meaning that you can have a stylesheet that only applies when you're printing a page, allowing you to cause it to be formatted differently.
Just include a media="print" attribute on your stylesheet link for that stylesheet.
This A List Apart article seems to be quite good on the subject.
I tried using different style sheets based on the media, but I ran into trouble getting all the options I needed in. Since then I usually redirect to a different entrance of our (Fusebox) framework (i.e. print.php in stead of index.php) which in essence is the same file except it sets an extra flag/constant.
In the XSL file associated with the page I then do additional work based on that flag/constant like leaving out the menu, columns of a table etc.
i.e. (Page shows a link that the user has to click to display the password on the screen. The print version has the password printed.)
if (!BOOL_PRINT)
echo "<TD class=\"tbl_teams_scroll_item\"><SPAN class=\"span_password_hidden\" id=\"span_password_{\$team_id}\" onClick=\"RevealPassword('{\$team_id}','{\$password}');\"><xsl:value-of select=\"/PAGE/TEXTS/HIDDEN\" /></SPAN></TD>\n";
else
echo "TD class=\"tbl_teams_scroll_item\"><xsl:value-of select=\"PASSWORD\" /></TD>\n";
You can define css rules that are specific to a media type. The following is a css example (copied from http://www.w3.org/TR/CSS2/media.html, section 7.2.1) that specifies different font sizes what gets displayed on a web page and what gets printed.
#media print {
BODY { font-size: 10pt }
}
#media screen {
BODY { font-size: 12pt }
}
#media screen, print {
BODY { line-height: 1.2 }
}
Alternatively, you can specify what media a stylesheet should be applied to when including it in a page:
<link href="webstyles.css" type="text/css" rel="stylesheet" media="screen"/>
<link href="printstyles.css" type="text/css" rel="stylesheet" media="print"/>
<link href="commonstyles.css" type="text/css" rel="stylesheet" media="screen,print"/>
Yet another option is to have a hidden IFRAME that you call iframe.contentWindow.print() on. That will allow you to create an invisible layout that prints exactly as you want it to.
Of course, an even better solution is to export the file to a PDF and let the user print it out that way. PDFs produce the highest quality output, period. However, it is one more hoop for the user to jump through, so the rule of thumb is:
PDFs for when the print layout matters
HTML for when the pure text is more important than the layout
Anything you can do with CSS you can do in a print stylesheet. This means you can hide content in the print version which is shown in the screen version or hide content in the screen version which you want to show up when printing.All you do is apply display:none to the appropriate sections in the appropriate stylesheet.
Also it is a good idea to size your text in points for the print version (which is a bad idea for the screen version - stick to pixels, ems or percentages here). There is universal agreement as to what printed point sizes are where as mappings of pixels to points will vary with different resolution devices.
nsayer mentions having a print button change the layout of your screen and then kicking off a window.print()
This is a solution that will probably have been overlooked by a lot of people and should be considered when you think your users want a little more of a WYSIWYG. It should probably be a "printer friendly" link though that changes the media type of your sheet sheets rather than "print this".
Using jquery, you could do something like this (not checked):
$(document).ready(function(){
$("#printFriendly").click(function(){
$(link[rel=link][media=screen]).remove();
$(link[rel=link][media=print]).attr("media","screen");
});
});