How to Dynamically Load Dark Mode CSS with JavaScript

How to Dynamically Load Dark Mode CSS in your Website or WebApp (Ionic, React, or Angular):

1. Create the two separete css files, one for dark colors and one for bright
2. Upload those to your server to css folder
3. Use the script example below to load the appropriate css file based on the hours in the day.


function loadcssfile(filename, filetype){
    if (filetype=="css"){ //check filename is an external CSS file
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
}

var date = new Date();

 if (date.getHours() >= 19 || date.getHours() <= 7) // after 7pm before 7am
	loadcssfile("../css/darkmode.css", "css");
 else
	loadcssfile("../css/lightmode.css", "css");

Don't blind your readers at night -_-

If you want to incorporate sunset and sunrise you can look into Suncal library, but you will have to request user's location which is always rude and not recommended.

Style Ion-Radio checkbox in Ionic with CSS

Recently I had the trouble of changing the default radio checkbox in ionic. Here is the CSS of how to do this:

.list .item-radio .item-content {
  background-color: black;
  color: white;
}
.list .item-radio .radio-icon {
  background-color: black;
  color: white;
}
.item-radio input:checked + .radio-content .item-content {
    /* style the item content when its checked */
    background: black; 
}

How To Vertically Align Div Element

There are many ways to do this (allegedly), but here’s how I’ve vertically aligned an element inside a div:

In CSS:

.center { 
    height: 200px;
    position: relative;
}

.center p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

In HTML:

<div class="center">
  <p>This should be centered</p>
</div>