I have a small website using only PHP, HTML, and CSS and want to add Dark Mode on it. I've found a lot solutions, but all of them use JavaScript. Is that possible to add Dark Mode without JS?
One option could be to use a routing element in your URL that determines (using server side logic) which set of cascading style sheets gets loaded.
For example in http://foobar.com/dark/path/to/content the /dark/ part of the URL could make the server load your "dark" theme CSS files.
You already have all you need. Browser detection is done with CSS following the Media Queries Level 5 specification using a prefers-color-scheme media query for detection. If you're familiar with responsive web-design with CSS then you already have all the knowledge - the only difference is that responsive CSS is about geography (sizes, columns, padding, spacing, font-size, etc.) and prefers-color-scheme is about ... well ... color. Thomas Steiner (#DenverCoder9) has an awesome article "prefers-color-scheme: Hello darkness, my old friend" that covers this.
If you are asking about PHP specifically then you are out of luck - there is no dark mode detection methodology for server side-processing.
All efforts thus-far by the W3C (and its sponsors) has been focused on client-side / Jamstack.
There is a recommendation by Thomas Steiner (same guy) to implement a Proposed server-side client hint, but this has not been adopted (yet?) by the W3C or the browsers.
Either way - there is a significant drawback in server-side detection (both with Thomas' recommendation and my solution below) in that the server will only know about a state change (e.g. macOS "Auto" mode when night fall happens) on the next server request, or more visibly, the first load of the page.
My recommendation is to leverage CSS / client-side only on this - Thomas gives some practical guidance on two methods,
1x CSS with both color schemes supported, and
2x CSS, with one being light and the other dark. I've made a educative whitepaper applying some of these methods with the CSS framework Bootstrap at vinorodrigues/bootstrap-dark to show how easy that can be - without server-side processing.
Having said that - if you must insist on PHP or server-side detection there is no workaround - but one must use some JS. The most efficient way is to leverage the js-cookie/js-cookie project, and include the following code into your HTML pages:
<script src="https://cdn.jsdelivr.net/npm/js-cookie/dist/js.cookie.min.js"></script>
<script>
// code to set the `color_scheme` cookie
var $color_scheme = Cookies.get("color_scheme");
function get_color_scheme() {
return (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light";
}
function update_color_scheme() {
Cookies.set("color_scheme", get_color_scheme());
}
// read & compare cookie `color-scheme`
if ((typeof $color_scheme === "undefined") || (get_color_scheme() != $color_scheme))
update_color_scheme();
// detect changes and change the cookie
if (window.matchMedia)
window.matchMedia("(prefers-color-scheme: dark)").addListener( update_color_scheme );
</script>
And then your PHP will detect this cookie like this:
$color_scheme = isset($_COOKIE["color_scheme"]) ? $_COOKIE["color_scheme"] : false;
if ($color_scheme === false) $color_scheme = 'light'; // fallback
Which you can use to load the CSS:
// Load the CSS for the correct color-scheme
if ($color_scheme == 'dark') {
?><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/vinorodrigues/bootstrap-dark#0.0/dist/bootstrap-night.min.css"><?php
} else {
?><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0.css/bootstrap.css"><?php
}
Or, like this:
?>You are in <?= $color_scheme ?> mode.<?php
You can do a clone of the css and change the background-color, buttons... It's not really necessary really to use JavaScript
If you want to do just a button for change the css, i don't really know how to do it, but if you want to do another webpage but just for Dark Mode, just put the clone off the css that you created.
Related
In my responsive WordPress theme using Twitter Bootstrap, I'm trying to use a technique similar to CSS Conditional loading but relying on PHP instead of Javascript minimize from so many requests loading.
What I'd like to do is use PHP to detect the :after pseudo element content property to see which element is loading based upon the media query/viewport size of the browser.
Here's example CSS:
body:after {
display: none;
/* Default */
content: "A";
}
#media (min-width: 35em) {
body:after {
content: "B";
}
}
To be very specific, if PHP can detect that content: "A" is active, it will load custom_mobile_content() hook which renders mobile content. If it detects content: "B", it will load custom_desktop_content() hook which renders more desktop content.
I tried using the javascript version but it requires I put a large block of formatted HTML into a javascript variable and upon rendering of the page there's a huge block of text that's inactive and unused on the page contained within the javascript. PHP seems to be a better fit.
Is there code which can produce this easily?
EDIT: It appears that I'd have to pass a JS variable or function to PHP in order for this to work, and I suppose that's pretty complicated.
Here's the javascript I'm trying to work with:
$(function() {
var currentSize = "A";
$(window).resize(function() {
var size = window.getComputedStyle(document.body, ':after').getPropertyValue('content');
/* Ridiculous thing to deal with inconsistent returning of
value from query. Some browsers have quotes some don't */
size = size.replace(/"/g, "");
size = size.replace(/'/g, "");
if (size != currentSize) {
if (size == 'B') {
$(".content").load('<?php custom_hook(); ?>');
currentSize = 'B';
}
}
}).resize();
}
I've included the above code in the WordPress page itself because it doesn't need to be cached in a file. It is only used once and on this page. However, the problem with this is that the custom_hook() code is rendered on the page and that hook includes a bunch of markup. If the javascript determines that I'm using A, all that markup is on the page in the source code for no reason. I want to find a way to prevent the custom hook from rendering UNLESS it's being used in B. Hope that makes sense.
At the moment there's no reliable way to detect pseudo-elements, even in JavaScript. They have no CSS Object Model (CSSOM). PHP can't help you in this situation either because it acts only server-side.
For an alternate workflow, you can use JavaScript to find out which media query is currently active. Based on this you can load other resources if necessary.
See this article on MDN for details on how to work with media queries from JavaScript.
How can I detect if an iPhone has a retina display or not? Is there a reliable way? Either pure PHP or preferably Zend Framework way of doing this.
i figure it out by this
var retina = window.devicePixelRatio > 1;
if (retina)
{
// the user has a retina display
}
else
{
// the user has a non-retina display
}
You must consider the fact that you are trying to get client side information on the server side.
It would seem that you are unable to detect the display with pure PHP or Zend framework.
It furthermore seems like the UserAgent information from the client, that you might access from PHP is based upon the OS, not the hardware, and thusly does not help you.
You might be interested in reading the following article which much more eloquently and thoroughly explains the issues.
http://www.bdoran.co.uk/2010/07/19/detecting-the-iphone4-and-resolution-with-javascript-or-php/
Good luck!
Javascript: window.devicePixelRatio
I guess as simple thing as display width detection would be sufficient for such a task, retina display packs so many pixels in the width, that simple check will immediately tell you if its an ordinary display or retina display.
PHP does not have such a capability out of a box, but Javascript does.
Here is how :
<script language="Javascript">
<!--
document.write('<br>your resolution is' + screen.width + 'x' + screen.height)
//-->
</script>
Hi I want to detect ipad orientation in php, i know i can detect the iPad but how do i detect the orientation, i need it in php and not css because i want to show x pictures in my gallery in portrait and x in landscape.
here is the code i am using to detect the php for iPad:
if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') !== FALSE) {
} else {
}
i have checked on this site and on google but was unable to find anything which could help
thankyou
iPad orientation can change when the user holds her iPad differently. Therefore, there's no point of registering it in php - by the time your response reaches the client, it might already be different.
If there needs to be any plumbing that can't be done in CSS (like loading different images or so), handle the orientationchanged event in JavaScript.
This is not orientation detection but USER AGENT detection. It only detects what kind of browser is browsing your page.
Are you trying to detect the device or what way the device is rotated?
I believe you would have an easier time detecting the orientation of a device either in Javascript or CSS, have you looked into these yet?
Javascript:
<button onclick="detectIPadOrientation();">What's my Orientation?</button>
<script type="text/javascript">
window.onorientationchange = detectIPadOrientation;
function detectIPadOrientation ()
{
if ( orientation == 0 ) {
alert ('Portrait Mode, Home Button bottom');
}
else if ( orientation == 90 ) {
alert ('Landscape Mode, Home Button right');
}
else if ( orientation == -90 ) {
alert ('Landscape Mode, Home Button left');
}
else if ( orientation == 180 ) {
alert ('Portrait Mode, Home Button top');
}
}
</script>
CSS
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
The device orientation is dynamic - the user can rotate the device after the page has been loaded. Therefore, it makes no sense to include it in the user agent string.
Instead, you should use HTML and JavaScript to change the layout when the orientation changes.
Everyone is suggesting you do it in Java Script which is completely correct but I'm guessing you don't see that as an option from your question.
You should load enough images (or all if not a stupid number, it is only a URL string after all) from PHP to fill the largest size in JSON (json_encode($array of image URL's to use)) format. Then use JavaScript to detect orientation and populate the page with the correct number/layout of images.
You'll have an array in JavaScript of Image URL's to pick from and load dynamically.
use this code may be use full to you
var orient = Math.abs(window.orientation) === 90 ? 'landscape' : 'portrait';
A brutal way would be to store the orientation change in a cookie through jQuery and access it with the $_COOKIE variable in php.
However, you would still need the javascript hooks to detect the orientation change and possibly a page reload.
I am having trouble using a script I found at http://www.marcofolio.net/webdesign/use_a_custom_font_on_your_website.html
The problem is, when I load a page, the text shows up then each word is replaced by a generated image of it using the PHP GD lib.
It creates a flicker effect that I can't seem to get rid of. There are options is the js file:
var hideFlicker = true;
var hideFlickerCSS = "replacement-screen.css";
var hideFlickerTimeout = 0;
But when I change any of those settings, nothing happens.
Please help!
Thank you.
For what you seem to be trying to do, image replacement is an extremely outdated method. All the ninja-devs are using technology called #font-face for their fonts and font replacements.
It's simpler, doesn't require anything to happen on the server and text on the page can be modified dynamically.
You can use services like http://www.fontsquirrel.com/ or http://code.google.com/webfonts for ready made font packages.
If you have a custom font (that you have a license for) you can create an #font-face package for it, using fontsquirrel's #font-face generator: http://www.fontsquirrel.com/fontface/generator
And then you just define your fonts in the CSS. Simple, elegant and works in 99% of browsers (yes, even IE6)
Cheers!
I need some help writing an awesome class to take a style sheet, detect browser specific CSS3 rules, and add support for all compatible browsers. This way, we can just write our styles sheets for one browser and then process the CSS files when we are ready for production.
Here's my thoughts on the class so far:
class CssRewriter {
public function reformCss($file) {
// Get the CSS as a string
$cssString = file_get_contents($file);
// Use regex to capture all styles delimited by {...}
// Use regex to determine if the any of the captured styles are browser
// specific (starts with -moz, -webkit, etc)
// Determine which CSS3 rules are not present and add them to the style
// (so if you have -moz-linear-gradient, automatically add the webkit
// version)
}
}
Yikes. CSS parsers are not as easy as you imagine, man. Depending on regular expressions is just asking for one typo to be totally misinterpreted.
Not the answer you were looking for, but quite possibly a better one: have you considered using Sass and mixins? You're not the first to hit the issue of the repetitive nature of CSS, so someone else has already faced the challenge of a CSS pre-processor for you.
Your best bet would be to modify existing CSS parser like CSS Tidy and add in a additional logic to output backwards-compatible CSS.