Applying margin to a background image with fixed position - javascript

I have a background image that I want to cover my entire screen minus the header. I also don't want my background image to scroll. It should not move as the user scrolls over content.
For this reason I use the following to place my background:
<div
className={style.app}
style={{
backgroundImage: `url(${HomePhoto})`,
backgroundRepeat: "no-repeat",
backgroundAttachment: "fixed",
}}
></div>
I am attempting to add additional CSS properties to assume the proper height and width are used:
height: 100vh;
width: 100vw;
margin-top: 4rem;
background-size: 100% 100%;
However the margin-top is not applied unless I remove backgroundAttachment: "fixed". Is there a way I can achieve both styles?

You can use the backgroundPosition property which allows you to move a background image around in its container: https://developer.mozilla.org/en-US/docs/Web/CSS/background-position
<div
className={style.app}
style={{
backgroundImage: `url(${HomePhoto})`,
backgroundRepeat: "no-repeat",
backgroundAttachment: "fixed",
backgroundPosition: "100px 0", // or vh
}}
></div>

Related

ReactJS CSS inline style position dynamically

I have this element in my React code:
{focusedAnnotationIconProps && (
<div
style={{
backgroundColor: "#333",
width: "100px",
position: "absolute",
left: focusedAnnotationIconProps.left,
top: focusedAnnotationIconProps.top + 25,
color: "#fff",
}}
>
{annotationIconPopoverText}
</div>
)}
this is a popover that will show when hovering over an icon, so I get the CSS left/top position numbers from that Icon (in another part of the code), and place it there, and currently, is showing like this:
I need to center this popover in the middle of the icon
but the thing is, this <div> element has variable width, depending on the text inside
so I was thinking of someway to do something like this:
left: focusedAnnotationIconProps.left - this.width/2
but I know that won't work.. I tried using the calc css3 function, but won't work inline with CSS, so there's my problem.. would appreciate any help
With position: absolute, you can use these methods to center the elements:
Center Vertically:
style={{
top: "50%",
transform: "translateY(-50%)"
}}
Center Horizontally:
style={{
left: "50%",
transform: "translateX(-50%)"
}}
Center to the parent div:
style={{
left: "50%",
top: "50%",
transform: "translate(-50%, -50%)"
}}

Make CardMedia Images fit its content in MUI 5

I want my images to fully fit the CardMedia. Yet since they are of different heights and widths, some of them get cut like so:
Also upon resizing, some images get cut as well:
This is the code for the CardMedia part:
<Card
raised
sx={{
maxWidth: 280,
margin: "0 auto",
padding: "0.1em",
}}
>
<CardMedia
component="img"
height="250"
image={product.img_urls[0]}
alt={product.name}
title={product.name}
sx={{ padding: "1em 1em 0 1em" }}
/>
// Other Content
</Card>
Overall, I want to achieve something like this but with all the cards in the same height and width:
Is there any way I can fix this or do I need to resize each image individually?
You need to make your pictures to fill their layouts, AND keep their aspect ratio.
The best way is to set their "object-fit" css property to "contain".
Try this:
<Card
raised
sx={{
maxWidth: 280,
margin: "0 auto",
padding: "0.1em",
}}
>
<CardMedia
component="img"
height="250"
image={imageNetwork}
alt={"alt"}
title={"titleasdasdsada"}
sx={{ padding: "1em 1em 0 1em", objectFit: "contain" }}
/>
// Other Content
</Card>
Try this
parent-image-element {
width: 100px;
}
image {
width: 100%;
max-height: 100px;
}

Next JS image centering while screen size increases

I've been having a tough time working with NextJS's Image component.
I want to setup a banner image. This image must only cover a certain amount of space on the screen at any time, regardless of screen size. I've gotten this to mostly work with the combination of max-height: 30vh and overflow: hidden. However, I can't seem to get the image to center while the screen size changes. It should vary from seeing the entire image to focusing on the bed. Instead, its focusing on the pic's ceiling.
Live sample: https://codesandbox.io/s/nextjs-image-layout-lc7vb?file=/src/pages/index.tsx
const Index = (props: IBlogGalleryProps) => (
<Main
...
>
<div className="w-full overflow-hidden" style={{ maxHeight: '30vh' }}>
<Image width="300" height="200" layout="responsive" src="https://images.unsplash.com/photo-1519494080410-f9aa76cb4283?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1920&q=80" />
</div>
...
</Main>
);
If you want to align the image according to your needs, you should use layout="fill" with eg. objectFit="cover".
next/image API Reference
When fill, the image will stretch both width and height to the dimensions of the parent element, usually paired with object-fit.
For this to work, the container needs a height and position: relative.
You can also set objectPosition if you don't want the CSS's default object-position: 50% 50%.
This should do the trick:
const Index = (props: IBlogGalleryProps) => (
<Main
...
>
<div className="w-full overflow-hidden relative" style={{ height: '30vh' }}>
<Image layout="fill" objectFit="cover" src="https://images.unsplash.com/photo-1519494080410-f9aa76cb4283?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1920&q=80" />
</div>
...
</Main>
);
Here is an working example: https://codesandbox.io/s/nextjs-image-layout-forked-82op5?file=/src/pages/index.tsx
#El Devoper's answer is the correct approach, but for version 13+ the objectFit and layout props have been removed. Instead you need to use the style prop.
Version 13+
<Image fill style={{ objectFit: "cover" }} />
<div
style="
height: 30vh;
width: 100%;
max-width: 800px;
position: relative;
background-image: url('/imagelink/image.jpg');
background-position: center center;
background-size: cover;
">
</div>
you could use a div and set to it a background.
What you call fixing on the bed are done with the background-position tag.
But you can also use object-fit and object-position for the <img/> tag.
like this:
object-fit: cover;
object-position: center;
this will make you image always 100% width and height of the <img/> box size and also center it.

How to vertically and horizontally center a component in react?

How can I achieve absolute centering with CSS-in-JS? When I use the following code, my component moves across the screen. I guess the translate is being applied many times instead of just once. What's going on, and how can I fix it without using a library?
render() {
return (<ComponentASD
style={{
position: 'absolute', left: '50%', top: '50%',
transform: 'translate(-50%, -50%)'
}} />);
}
Another option is to use flex-box.
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
Hello world
</div>
Your example code works well:
ReactDOM.render(
<div
style={{
position: 'absolute', left: '50%', top: '50%',
transform: 'translate(-50%, -50%)'
}}
>
Hello, world!
</div>,
document.getElementById('root')
);
https://codepen.io/anon/pen/JaLLmX
It has to do something with your layout.
Thanks for the testing+comments! The styling ended up being fine, the issue was somehow caused by the layout of ComponentASD, which is actually MUI's CircularProgress https://material-ui.com/api/circular-progress/#demos
I wrapped that component in a div inside of render and applied the styling to the div, which fixed the problem (keeps it stationary and properly aligned).
This is flexbox you will need to use this on the parent Component.
.Parent {
display: flex,
flexFlow: row nowrap,
justifyContent: center,
alignItems: center,
{
It will center the children vertically and horizontally
You can also align each component as I've shown you below
render() {
return (<Childcomponent
style={{
display: flex,
flexFlow: row nowrap,
justifySelf: center,
alignSelf: center,
}} />);
}
If you want to have a properly scrollable list if the window's height is smaller than the content's height you want to center, you can do this (based on this CSS answer):
<div
style={{
display: "table",
position: "absolute",
height: "100%",
width: "100%",
top: 0,
left: 0
}}
>
<div
style={{
display: "table-cell",
verticalAlign: "middle",
textAlign: "center"
}}
>
// Here comes the content you want to center
</div>
</div>
If you want to use it in a component just call it in the component:
.Login {
text-align: center;
background-color: #2681C6;
min-height: 100vh;}
Your jsx file sould have something like just to call it, using "className":
<div className="Login"><div>

Make left and right margins equal when outer component is not known

I want to display the following image centered:
I have the following style item:
var itemStyle = {
display: 'block',
width: this.computeWidth(),
height: '250px',
backgroundImage: 'url(' + imageLocation + ')',
backgroundPosition: 'center !important',
backgroundSize: 'cover',
boxShadow: '10px 10px 5px #888888',
borderRadius: '15px',
marginLeft: 'auto !important',
marginRight: 'auto !important'
};
Which I display like this:
<div style={itemStyle}>
</div>
this.computeWidth() is this method, where I resize the width of the image depending on the page:
computeWidth: function() {
console.log("this.state.window.width: " + this.state.window.width);
if(this.state.window.width > 350) {
return '250px';
}
return Math.floor(0.7 * this.state.window.width).toString() + 'px';
},
I also tried computing marginLeft and marginRight using this method:
computeMargin: function() {
if(this.state.window.width > 350) {
return 'margin-auto';
}
return Math.floor(0.15 * this.state.window.width).toString() + 'px';
},
However, the image was not centered again.
So how can I make sure that the image is central to the page?(preferably without changing the css of the component containing it)
What's wrong with margin: Xpx auto? It should work, because the image as defined width. Alternatively, you can add flexbox properties to the parent in order to center the child:
.parent {
display: inline-flex;
justify-content: center;
width: 100%;
}
CSS should be enough to solve this problem. Wrap the image in a div and center that with margin property.
<div class="img-wrap">
<img src="foo.jpg">
</div>
.img-wrap { margin: 0 auto; }
Refer here for more detail: CSS-Tricks centering guide
Edit
- For centered background image apply the following CSS to the div:
background-image: url("foo.jpg");
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: contain; /* Full image in div, no cropping, preserve aspect ratio */
This centers the image by moving the image's center halfway along both axes (x and y) in the div. Thus, perfect centering.
Alternatively, use this for hero images:
background-size: cover; /* Fill div (even if img is cropped), preserve aspect ratio */
More for background centering: Sitepoint: background-position property

Categories