- In Django, you can write CSS (Cascading Style Sheets) code to style your web pages. CSS is used to control the layout, appearance, and design of your HTML elements. To integrate CSS into your Django project, follow these steps:
- First, create a CSS file where you'll write your CSS code. You can create this file in any directory within your Django project. For example, let's create a CSS file called "style.css" inside a directory called "static/app/css" in your Django app. Your directory structure might look like this:
- Django requires a configuration to serve static files like CSS. In your Django project's settings.py file, make sure the following settings are properly configured:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
- This configuration tells Django where to look for static files.
- To use your CSS file in an HTML template, you need to link it in the `<head>` section of the HTML file. Django provides a built-in template tag called `{% static %}` to generate the correct URL for the static file. Add the following code to your HTML template file:
- templates/app/index.html
{% extends "base.html" %}
{% load static %}
{% block importCdn %}
<link rel="stylesheet" type="text/css" href="{% static 'css/app/style.css' %}">
{% endblock %}
{% block title %}App - My Website{% endblock %}
{% block content %}
<h2 class="heading-style">Welcome to the App Page</h2>
<p>This is the content of the Django App page.</p>
{% endblock %}
- This code imports your CSS file into the HTML template and use it.
- Now you can start writing your CSS code inside the "style.css" file you created earlier. For example:
- static/css/app/style.css
.heading-style {
color: red;
font-size: 25px;
}
- To see the CSS changes on your web page, run the Django development server by executing the following command in your terminal or command prompt:
python manage.py runserver
- Now, when you open the corresponding web page, you should see the CSS styles applied.
- That's it! You have successfully written CSS code in Django. Remember to make sure your CSS file is properly linked in your HTML template and that the static files configuration in your Django settings is correct.
No comments:
Post a Comment