Tainara
Tainara

Reputation: 337

How to crop and center an image with CSS?

I'm still a beginner with CSS and I'm not able to adjust an image as I was request in zeplin.

The original image is quite tall, and in the zeplin the image is cut and shows only the center, with the model in the pic. As you can see in the image below

enter image description here

Can you tell me how to adjust the image in the same way as it is in Zeplin? I put my code into codesandbox.

import "./styles.css";
import Art1 from "./images/art_home_1.png";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div className="images">
        <img src={Art1} alt="" />
      </div>
    </div>
  );
}
.App {
  font-family: sans-serif;
  text-align: center;
}

.images {
  width: 100%;
  max-width: 720px;
  height: 720px;
  overflow: hidden;
}

img {
  width: 100%;
  height: auto;
}

Thank you in advance for any help.

Upvotes: 0

Views: 219

Answers (3)

Sedki Sghairi
Sedki Sghairi

Reputation: 379

You can get rid of the div surrounding the img, and just use object-fit property to make the image cover the available space. It is responsive and much better practice than dealing with position absolute. your app.js will look something like this:

import "./styles.css";
import Art1 from "./images/art_home_1.png";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
        <img src={Art1} alt="" className="images" />
    </div>
  );
}

Styles.css:

.images {
  width: 100%;
  max-width: 720px;
  height: 720px;
  object-fit: cover;
}

Your image will be responsive, it will be full on small screens and you can adjust the max-width property of images className to get your desired output for bigger screens.

Upvotes: 1

0stone0
0stone0

Reputation: 43954

Onother option is to set the image as a background-image so you can use the css propertys like background-position to align the image.

<div className="images" style={{ backgroundImage: `url(${Art1})` }}></div>
background-position: bottom;

enter image description here

Upvotes: 1

Behemoth
Behemoth

Reputation: 9310

You can position your image relative and then move it as you wish. This should be quite accurate to the image you provided above:

import "./styles.css";
import Art1 from "./images/art_home_1.png";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div className="images">
        <img src={Art1} alt="" />
      </div>
    </div>
  );
}
.App {
  font-family: sans-serif;
  text-align: center;
}

.images {
  width: 100%;
  max-width: 720px;
  height: 720px;
  overflow: hidden;
}

img {
  position: relative;
  top: -350px;
  width: 100%;
  height: auto;
}

Upvotes: 1

Related Questions