Почему не подключается css к html
Перейти к содержимому

Почему не подключается css к html

  • автор:

How to fix CSS not linking to your HTML document

When working with HTML and CSS, you may find that your CSS is not styling your HTML document even when you’ve added the CSS to your page.

Here are six fixes that you can try to make your CSS work on your HTML page

Make sure that you add the rel attribute to the link tag

When you add an external CSS file to your HTML document, you need to add the rel="stylesheet" attribute to the <link> tag to make it work.

If you omit the rel attribute from the <link> tag then the style won’t be applied to the page.

Make sure you have the correct path in the href attribute

If you have the CSS file in the same folder as the HTML document, then you can add the path to the CSS file directly as shown below:

If you add a / before the file name, the CSS won’t be applied:

When your CSS is one folder away, you need to specify the folder name inside the href attribute without the / as well.

This is wrong:

This is correct:

Make sure the CSS file name is correct

The name of the CSS file that you put inside the href attribute must match the actual name of the CSS file.

If you have a CSS name with spaces, then you need to include the spaces in a URL-safe format by replacing it with %20

For example, suppose the name of your CSS file is my style.css , then here’s the correct name inside the href attribute:

Because URL can’t contain spaces, it’s recommended that you replace all spaces in your CSS file with a hyphen — or an underscore _ so that my style.css becomes my-style.css or my_style.css .

Make sure the link tag is at the right place

The <link> tag that you used in your HTML file must be a direct child of the <head> tag as shown below:

If you put the <link> tag inside another valid header tag like <title> or <script> tag, then the CSS won’t work.

The following example is wrong:

The external style CAN be put inside the <body> tag, although it’s recommended to put it in the <head> tag to load the style before the page content.

The following example still works:

Make sure that all your style rules are correct

When you have an invalid CSS syntax inside your stylesheet, then the browser will ignore the invalid syntaxes and apply the valid ones.

For example, suppose you have the following CSS file:

Because browsers have no support for choco color name, the style rule for <h1> tags above will be ignored while the background-color property for the <body> tag will be applied.

Make sure that you are using the right syntax for your styling because invalid CSS syntax won’t generate an error message.

Invalidate the cache with a hard reload

Sometimes, you might have the CSS file linked correctly from your HTML file, but you don’t see the changes you make to the CSS file reflected on the web page.

This usually happens when the browser serves a cached version of your CSS file.

To invalidate the cache and serve the latest version of your CSS file, you can perform a hard reload on the browser.

The shortcut to perform a hard refresh might vary between browsers:

  • For Edge, Chrome, and Firefox on Windows/ Linux, you need to press Shift + CTRL + R
  • For Edge, Chrome, and Firefox on macOS, you need to press Shift + CMD + R
  • For Safari, you need to empty caches with Option + CMD + E or click on the top menu Develop > Empty Caches

If you’re using Chrome, you can also select to empty the cache and perform a hard reload with the following steps:

  • Open the Chrome DevTools by pressing Shift + CTRL + J on Windows/ Linux or Option + CMD + J on Mac.
  • Right-click on the reload (refresh) icon and select the third option

The image below shows the Chrome Empty Cache and Hard Reload option you need to select:

With that, you should see the latest CSS changes reflected on your web page.

Alternatively, you can also invalidate the browser cache by using CSS versioning as explained here:

And those are the six fixes you can try to link your CSS file to your HTML document.

I hope this tutorial has helped you fix the issue ��

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

Ezoic

report this ad

About

Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.

Free Code Snippets Book

Get my FREE code snippets Book to 10x your productivity here

Ezoic

report this ad

Не подключается css к html. как исправить ошибку?

1. Проверьте, что файл style.css точно существует (в браузере нажмите на ctr + u и нажмите на название файла и физически в папке проверьте, что файл style.css есть), а также проверьте, что все символы в английской раскладке клавиатуры

2. Попробуйте поставить слеш так:

  1. файл проверил он есть (когда выполнил действие в браузере открылся файл этот)
  2. слеш поставил но не получилось получилось (т.е после того как поставил слеш заголовок сайта поднялся в самый вверх, когда его убрал, заголовок спустился чуть ниже, значит ссылка правильная

.header<
background-color: darkslateblue;
height: 177px;
font-size: 0.8em;
margin-left: 0px;
margin-right: 0px;
min-width: 900px;
>

.main, .logo, .menubar, .size_content, .foother,<
margin-left: auto;
margin-right: auto;
>

HTML not loading CSS file

I am completely stumped as to why this doesn’t work. It seems the HTML file can’t load the CSS for some reason, even though both are in the same directory. Any idea what might be the problem?

The above doesn’t work. Adding the css inline in index.html works fine though

Husen's user avatar

26 Answers 26

to your link tag

While this may no longer be necessary in modern browsers the HTML4 specification declared this a required attribute.

type = content-type [CI]

This attribute specifies the style sheet language of the element’s contents and overrides the default style sheet language. The style sheet language is specified as a content type (e.g., "text/css"). Authors must supply a value for this attribute; there is no default value for this attribute.

Check both files in the same directory and then try this

As per you said your both files are in same directory. 1. index.html and 2. style.css

I have copied your code and run it in my local machine its working fine there is no issues.

According to me your browser is not refreshing the file so you can refresh/reload the entire page by pressing CTRL + F5 in windows for mac CMD + R.

Try it if still getting problem then you can test it by using firebug tool for firefox.

For IE8 and Google Chrome you can check it by pressing F12 your developer tool will pop-up and you can see the Html and css.

Still you have any problem please comment so we can help you.

w3uiguru's user avatar

You have to add type=»text/css» you can also specify href=»./style.css» which the . specifies the current directory

I have struggled with this same problem (Ubuntu 16.04, Bluefish editor, FireFox, Google Chrome.

Solution: Clear browsing data in Chrome «Settings > Advanced Settings > Clear Browsing Data», In Firefox, «Open Menu image top right tool bar ‘Preferences’ > Advanced «, look for this image in the menu: Cached Web Content click the button «Clear Now». Browser’s cache the .css file and if it has not changed they usually won’t reload it. So when you change your .css file clear this web cache and it should work unless a problem exists in your .css file. Peace, Stan

Stan Ralph's user avatar

Your css file should be defined as UTF-8. Put this in the first line of you css file.

With HTML5 all you need is the rel , not even the type .

<link href=»custom.css» rel=»stylesheet»></link>

sharkySharks's user avatar

Well I too had the exactly same question. And everything was okay with my CSS link. Why html was not loading the CSS file was due to its position (as in my case).

Well I had my custom CSS defined in the wrong place and that is why the webpage was not accessing it. Then I started to test and place the CSS link to different place and voila it worked for me.

I had read somewhere that we should place custom CSS right after Bootstrap CSS so I did but then it was not loading it. So I changed the position and it worked.

Hope this helps.

rbashish's user avatar

Also make sure your link tag’s media attribute has a valid value, in my case, I was using WordPress CMS and passed the boolean value true in the media field so it showed like that.

That’s why it was giving error. There are three main attributes on which the css style loading depends.

How to Fix CSS not working with VS Code

One annoying that comes up when working on front-end or web designs, the CSS does not seem to work when working with VS Code.

In this post, I will go over various problems that you can encounter and the possible fixes.

Steps to troubleshoot CSS loading issues in VS Code:

  1. Check that we have linked the right CSS file and using the correct path
  2. Check the file extension
  3. Review the link syntax and the CSS file and make sure it is valid
  4. Use browser (eg Chrome) DevTools to clear cache and check for errors

1. Check that we have linked the right CSS file and using the correct path

The most common problem with CSS not working with any editor (such as VS Code) is that we are using relative paths and got the path wrong!

  • / — This means the root directory
  • ../ — This means going up on directory
  • ./ — This means the current directory (if you are working off the current directory, you may not need this — just use the file name)
  • ../../ — This means going up two directories

Lets say we got the following basic folder structure

We can reference each of the files as below:

Please enable JavaScript

�� Tip: Use Live Server in VS Code!

If you are coding with VS Code, then using the Live Server extension is a must. When you are just coding locally without a local server running, references to images can get a bit confusing.

For example, if you use the root directory / — this could mean your actual C:/ root folder instead of the current folder!

Live server can be downloaded here: https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer

2. Check the file extension

One issue that can trip some people up is that the file names can be case insensitive. This will be based on the serve that is hosting your website.

With most Unix based servers (Linux, or OSX), the files are case sensitive. While on Windows servers, they are not.

As an example, if you are hosting with Apache on Ubuntu it does not care about your filename/ extension

In the example below, lets say we have stylesheet file called style.CSS , the second line will not load the CSS due to the all caps CSS extension

3. Review the link syntax and the CSS file and make sure it is valid

Commonly, we can link to a external stylesheet with the following <link> syntax:

  • keep the <link> tag within the <head> element. We can put it in the body, but best practice is to place it in the head section
  • Check that we include the rel=»stylesheet» — verify the spelling!
  • make sure to also have the correct type ( type=»text/css» ). This helps defines the type of the content. Having incorrect type could lead to the CSS not loading!
  • Check that you are not specifiying incorrect media

It is best to ignore the media attribute and use media queries in your CSS.

�� Tip: Use CSS validation services to check your CSS

Sometimes your CSS will not load might be due to malformed code (eg missing brackets, etc). Use tools like https://jigsaw.w3.org/css-validator/ to check!

4. Use browser (eg Chrome) DevTools to clear cache and check for errors

A common reason why you cant see your CSS changes is that the browser is caching the CSS.

What I usually do is to open up dev tools (Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux)) and tick the “Disable Cache (while DevTools is open)”

image on how to open DevTools and open its settings

This way we can ensure that our code is using the most up to date CSS.

Additionally, you can check if your CSS file is loading correctly by inspecting the console in DevTools. Usually if it is not showing, we can see a 404 error:

Summary

In this post, I went over some problems when loading external CSS files using VS Code and ways to fix them. The most common issue is using relative paths and getting the location wrong.

I would suggest to use absolute paths and use the VS Code Live Server extension to get around these issues.

We also need to check that our syntax and CSS is valid — correct spelling and not missing any brackets.

Finally we can check that the browser is not loading a cached version of our CSS. I would suggest to turn DevTools and check on the option of “Disable Cache (while DevTools is open)”!

�� About the Author

G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember ��)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *