简体   繁体   English

css 样式未应用于 html 中的 div

[英]css style not getting applied to a div in html

 .navigation-card{ background-image: url("https://www.sustainablewestonma.org/wp-content/uploads/2019/09/facebook-square-brands-blue.png"); background-repeat: no-repeat; background-position: center; height: 1000px; width: 700px; }
 <html> <head> <title>Webpage Components</title> <link rel="stylesheet" type="text/css" href="./Styles/main.css"> </head> <body> <div class="navigation-card"> </div> </body> </html>

It should show an image but its not.它应该显示图像,但不是。 The code works when I use a web link like above for the image but it doesn't work when I give a path of a local file on my computer.当我使用上面的 web 链接作为图像时,该代码有效,但当我在计算机上提供本地文件的路径时它不起作用。

You are usign image as background but you are not setting the background size, You just are setting the container size, so you have to add the next rule to your css class:您将图像用作背景,但您没有设置背景大小,您只是在设置容器大小,因此您必须将下一条规则添加到 css class 中:

background-size: contain;

or或者

background-size: 700px 1000px;

From: https://www.w3schools.com/cssref/css3_pr_background-size.asp来自: https://www.w3schools.com/cssref/css3_pr_background-size.asp

"contain" -> Resize the background image to make sure the image is fully visible “包含” -> 调整背景图像的大小以确保图像完全可见

The reason is it not centered is because you have set the width of the container to only 300px.原因是它没有居中是因为您将容器的宽度设置为仅 300 像素。 The image is taking up that full width.图像占据了整个宽度。 If you removed the width from navigation card, it will be centered.如果您从导航卡中删除宽度,它将居中。

Alternatively, you can add the following style to the card and it will center.或者,您可以将以下样式添加到卡片中,它将居中。

margin: 0 auto;

So you'll end up with this所以你最终会得到这个

.navigation-card {
    background-image: url("https://www.sustainablewestonma.org/wp-content/uploads/2019/09/facebook-square-brands-blue.png");
    background-repeat: no-repeat;
    background-position: center;
    height: 300px;
    width: 300px;
    margin: 0 auto;
}

to center a background image you shoud add margin: 50% auto;要使背景图像居中,您应该添加边距:50% auto; that make the image in the center of the page or margin: 0 auto;使图像位于页面或边缘的中心:0 自动; to make it in the top让它在顶部

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM