How to import images into CSS Modules? - css

I'm creating a website(creating using React). so I want to add a full-screen image for the Home page. I'm using CSS module. when importing an image into the module.css it's not rendered. How can I fix this. Here is my code. I'm importing this (scr => assets folder)
codesandbox-link
Home.js
import React from 'react'
import styles from '../styles/Home.module.css'
const Home = () => {
return (
<div className={styles.Hero} ></div>
)
}
export default Home
Home.module.css
.Hero {
background-image: url(../assets/hero.jpg);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}

It is CSS issue, your div, which is supposed to show the image in the background, has no height and width:
Background image is loading perfectly after adding below styles:
Global CSS (styles.css):
html,
body,
#root {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
App.module.css:
.Hero {
background-image: url(./assets/hero.jpg);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height: 100%;
width: 100%;
}
and in App.js:
import styles from "./App.module.css";
export default function App() {
return (
<div style={{ width: "100%", height: "100%" }}>
<div className={styles.Hero}></div>
</div>
);
}
I am not good at CSS. So, this may not be the perfect way to handle stylings (height / width). So, you may improve it. Here is the full code*.
As mentioned in docs, with webpack, you can load images in CSS as:
.Logo {
background-image: url(./logo.png);
}
Webpack finds all relative module references in CSS (they start with ./) and replaces them with the final paths from the compiled bundle.
*I provided full code as the image was not showing in codesandbox, but showing at my local machine.

Try this in a non-sandbox environment. The way you have imported className is fine.
I have a feeling sandbox is not reflecting it properly.
You can also try -
content:url(<path to image>);
in the className instead of background-image:url

I used the background in color and succeeded but the image didn't, you can import the image into App.js
import image from "./url";
return (
<img src={image} alt="" />
)

Related

Next.js return (failed)net::ERR_UNKNOWN_URL_SCHEME for imported images

I am using Next.js + styled-components + TypeScript. I want to use background-image: url() where I import image from assets folder present inside src folder. In network tab, when I look for images, it says in status:
(failed)net::ERR_UNKNOWN_URL_SCHEME and the url is
src:/_next/static/image/public/right.e158775f9c1cf296e36177bfb86a5ced.svg;height:32px;width:32px;
Which does not display image.
Assets folder is present in /src/assets/left.svg.
If I import the same image in index.tsx file and render it in Image component it works fine.
// styles.tsx
import styled from 'styled-components';
import Left from '../../assets/left.svg';
import Right from '../../assets/right.svg';
export const SwiperWrapper = styled.div`
margin-top: 2.5rem;
position: relative;
.swiper-position {
position: static !important;
}
.swiper-button-next:after,
.swiper-button-prev:after {
content: '';
}
.swiper-button-prev {
background-image: url(${Left});
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center;
-webkit-tap-highlight-color: transparent;
top: 100%;
}
.swiper-button-next {
background-image: url(${Right});
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center;
-webkit-tap-highlight-color: transparent;
}
`;
That is because in Nextjs, static files are served from the 'public' folder in the root directory. I suggest you store the images in this folder and reference them with a "/"
eg background-image: url('/Right');
Instead of moving all our images to public folder you can just use
background-image: url(${Left.src});
This is what worked for me:)
Note:
Actually Left will be an object if you try to console.log it, it will be something like:
{
blurDataURL: "/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fleft.475f00e5.png&w=8&q=70"
height: 1321
src: "/_next/static/media/left.475f00e5.png"
width: 1321
}

background image in styled components react

Good evening.
I am facing an issue while using react in combination with styled components.
I have an image folder located in :
And I have my styled components in the following folder :
Inside the styled components I'm trying to import the image like this :
const FormImage = styled.div`
width: 150px;
height: 150px;
margin: 0 auto;
margin-top: -20%;
background-image: url(../../img/testlogo.png);
`;
Im sure this is the right path. But somehow the image is not showing in the browser.
This is what i'm seeing in my browser :
Such path is not available in runtime (as CSS-in-JS like styled-component creates the CSS in runtime, although there are solutions with no-runtime), you should try one of the next approaches:
import ImgSrc from '../../img/testlogo.png';
const FormImage = styled.div`
background-image: url(${ImgSrc});
`;
// or
const FormImage = styled.div`
background-image: url(${require(`../../img/testlogo.png`)});
`;

How to override materialize css in React

I am using react to build simple app, and using Materilize css. In my UserProfile Component class importing UserProfile.css import "./UserProfile.css.
/* UserProfile.css */
.custom-class {
margin-top: 30 !important;
color: pink;
}
UserProfile in render method have
<h1 className="custom-class">Title</h1> // Margin is not applyed, but color is pink
I have an option to
<h1 style={{ marginTop: 30, color: "pink" }}>Title</h1>
this works fine, but I prefer style code in css files.
I am not sure maybe that issue has no relation to overriding.
you should use px in css files, change your code to margin-top: 30px !important; and it should work.
And if you want to check overriding issues in css, you can inspect your code(with right click your browser and choose inspect) and check if its crossed or not.
You'll need to use camelCase for your classname, so .customClass instead of .custom-class.
Then your import statement should look like:
import css from './UserProfile.css`;
and in your component:
<h1 className={css.customClass}>Title</h1>
Read up on CSS Modules for more information.
You don't have a unit for margin-top in your css class
.custom-class {
margin-top: 30px !important;
color: pink;
}

Only a few CSS files apply their styles in React

I am creating a ReactJs app, and am trying to apply styles. I load styles in the normal way (without webpack css modules):
import React, {Component} from 'react';
//styles
import './Header.css';
class Header extends Component {
render() {
return(
<div className='header'>
<h1>Save</h1>
</div>
);
}
}
The styles that I have for the header class apply, and everything is groovy. But for about 50% of my ReactJs files and their subsequent CSS files, the class styles do not apply. There is no error either, it finds the CSS and just doesn't apply the styles on some of the files.
I have no idea what is wrong, thanks!
EDIT 1
The header.css file:
.header {
width: 100%;
top: 0;
left:0;
text-align: right;
height: 100px;
margin: 0 auto;
}
.header h1 {
margin: 0;
margin-right: 40px;
cursor: pointer;
}
Edit 2
Example of class whose styles don't apply
Matrix.js:
import './Matrix.css';
render() {
const {users, selectedDivision} = this.state;
return(
<div className='container' style={{display:'grid', gridTemplateColumns:'200px 1fr'}}>
<div style={{textAlign: 'left'}}>
<input type='text' placeholder="Search Divisions" onChange={(e)=>this.search(e)} className='searchDivs'/>
<Scroller divisions={this.state.displayDivisions} handleSelectedDivisionChange={this.handleSelectedDivisionChange.bind(this)} />
</div>
<div style={{marginLeft: '10px'}}>
<Division division={selectedDivision} users={users} addToParentDivisions={this.handleNewUserAddedToDivision.bind(this)}/>
</div>
</div>
);
}
Here my work around has been to use inline styles but I want to try to avoid this as a best practice
Edit 3
Looking at dev tools in Chrome it shows that my css is not loaded because they are invalid property values?
So React is loading in the styles, but just refusing to display because they are invalid?
Just had the exact same problem!
Solution: Remove quotation marks (") around your property values.
Inline styles in JS require them but CSS does not.
I work in CSS every day I should've known this.
VSCode didn't pick it up either.
(Facepalm)
Assuming everything else is working properly like importing the right css file, using className, etc. I've found that, on rare occasions, something gets stuck in the browser cache and needs a full refresh.
Mac: Command+shift+R
Win: Ctrl+shift+R

Can't remove margins on react web app

I am having trouble removing these huge white margins on my react project. Below are some of the solutions I have tried.
* { margin: 0; padding: 0; }
/-/-/-/
body {
max-width: 2040px;
margin: 0 auto;
padding: 0 5%;
clear: both;
}
I have tried every variation. My only installed dependencies that should affect anything CSS wise is bootstrap and I don't think thats it. I tried adjusting max-width to a value of 2040px just to test if it would work and there appears to be a limit to which I can set the width. Help would be appreciated.
I should also mention that this is persistent throughout the entire page. This issue is not limited to the background image which I am linking in the css file
White Margins
All the browsers uses different default margins, which causing sites look different in the other browser.
The * is wildcard, means all elements present in our site (consider as universal selector), so we are setting each and every element in our site to have zero margin, and zero padding, to make the site look the same in every browsers.
If your style not getting applied then you can use !important to override style,
* {
margin: 0 !important;
padding: 0 !important;
}
If you created it using create-react-app there will probably be a file public/index.html.
There is a tag wrapped around the root where React will inject you App.
Usually the browser style-sheet set the margin of <body> to 8px.
That's most likely that white margin around your App that you're struggling to get rid off.
To remove it, one option is to open public/index.html and set the margin to 0 using inline styles like this:
<body style=margin:0>
In case you're using #emotion/react for styling you may alternatively (still assuming that there is this body tag in public/index.html) leave it as <body> and use the <Global> component to define styles for <body>. Something like this in your App.js:
function App() {
return (
<div>
<Global
styles={css`
body {
margin: 0;
}
`}
/>
<Your />
<Other />
<Components />
</div>
);
}
export default App;
User agent style sheet overrides the custom style. You can override this using !important in normal html and css
It is better to user react spacing library, rather than overriding the user default style sheet https://material-ui.com/system/spacing/
or you can use the following
<body id="body">
<div id="appRoot"></div>
</body>
style sheet
body
margin: 0
padding: 0
button
padding: 10px 20px
border-radius: 5px
outline: none
React JS code blocks
class A extends React.Component{
componentWillMount(){
document.getElementById('body').className='darktheme'
}
componentWillUnmount(){
document.getElementById('body').className=''
}
render(){
return (
<div> Component A </div>
)
}
}
class App extends React.Component{
constructor(){
super()
this.state = {
isAMount: false
}
}
handleClick(){
this.setState({
isAMount: !this.state.isAMount
})
}
render(){
return (
<div>
<button onClick={this.handleClick.bind(this)}> Click Me</button>
<div> App </div>
<hr />
<div> {this.state.isAMount && <A /> } </div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('appRoot'))
If you try:
* {
margin: 0 !important;
padding: 0 !important;}
You may have some issues. As I was using some mui, so this was distorting my components. I may recomend to modify the "body" in public/index.html using:
<body style=margin:0>
As you are using background image. Its problem due to image size ratio.
You have to use background-size: cover property in css.
Also use appropriate background-position to make sure the gavel comes in center bottom of page.
I was trying to add a background image in my react app but react left some margin on top and left.
const useStyles = makeStyles((theme) => ({
background: {
backgroundImage: `url(${Image})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
width: '100vw',
height: '95vh',
}
After reading the documentation, I realized that it was not margin, but positioning of the image. Setting the position:fixed with top:0 and left:0 fixed the issue.
After reading the answers above and trying them I have concluded that the best way is to keep your index.css(note: that the index.css in particular has the margins already set to 0 globally.) and App.css files that are auto generated when you "npx create-react-app".
I have noticed that many beginner tutorials tell you to remove these files and more, but after facing this problem it is honestly easier to just edit the boilerplate than start from scratch.
Simply add to the app.css or your main CSS file
body { margin: 0; padding: 0; }
* { margin: 0; padding: 0; } override by browser.
try
html,body{
margin:0;
padding:0;
}

Resources