So as per this directory structure, if we have style.css, it will be placed in assets/css/style.css. Similarly, our custom.js will have path assets/js/custom.js. Now, moving towards the process to learn how to include styles and scripts in the CodeIgniter website.
How to Load CSS in CodeIgniter
To load styles from external CSS files in CodeIgniter, we can opt any of the following methods.
Load CSS files in CodeIgniter by HTML <link> Tag
What we can do is, use link tag of HTML. Put this code in head section of the page. For example: Loading style.css with path as explained in the paragraphs above.
<link rel="stylesheet" href="<?php echo base_url(‘assets/css/style.css’) ?>" type="text/css" />
base_url() function will create your website URL (eg: http://myweb.com/) and the complete href value will be like http://myweb.com/assets/css/style.css
Another method to do so is by using the HTML helper function.
Load CSS files using link_tag() function
To load CSS files by using link_tag() function, we need to load html_helper. CodeIgniter’s html_helper enables the developers to write HTML elements without typing much HTML tags. What you need to do first is, open application/config/autoload.php. Scroll down to helpers section and add html_helper in autoload like I am doing below.
$autoload['helper'] = array('html');
And now put the code below in <head> section of your HTML page. Place it where you want to include the CSS. link_tag() function needs a few arguments mentioned below, which are treated as attributes of HTML <link> tag.
- Path of CSS file (href attribute).
- ‘stylesheet’ as rel attribute
- ‘text/css’ value of type attribute
- String for the title attribute
- Media value if you want to (all, print, etc)
- True/False for making the link to index page or not (false by default)
You need to pass at least one parameter, i.e. CSS file path, and others are your choice. Defaults are set for CSS inclusion.
<?php echo link_tag('assets/css/style.css'); ?>
<script src="<?php echo base_url('assets/js/custom.js'); ?>"></script>
base_url() function will create your website URL (eg: http://myweb.com/) and the complete src value will be like http://myweb.com/assets/js/custom.css