【问题标题】:How to crop and center an image with CSS?如何使用 CSS 裁剪和居中图像?
【发布时间】:2021-06-05 16:37:23
【问题描述】:

我还是 CSS 的初学者,我无法按照我在 zeplin 中的要求调整图像。

原始图像相当高,在 zeplin 中,图像被切割并仅显示中心,模型在图片中。如下图所示

你能告诉我如何像在 Zeplin 中一样调整图像吗?我将代码放入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;
}

提前感谢您的帮助。

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    另一个选项是将图像设置为background-image,这样您就可以使用background-position 等css 属性来对齐图像。

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

    【讨论】:

      【解决方案2】:

      您可以定位您的图像relative,然后随意移动它。这应该与您上面提供的图像相当准确:

      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;
      }

      【讨论】:

        【解决方案3】:

        你可以去掉 img 周围的 div,只使用 object-fit 属性使图像覆盖可用空间。与处理绝对位置相比,它具有响应性和更好的实践。 你的 app.js 看起来像这样:

        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>
          );
        }
        

        样式.css:

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

        您的图像将是响应式的,它会在小屏幕上充满,您可以调整 images className 的 max-width 属性以获得大屏幕所需的输出。

        【讨论】:

          猜你喜欢
          • 2018-04-13
          • 2019-12-10
          • 1970-01-01
          • 2021-11-24
          • 2012-07-18
          • 1970-01-01
          • 2013-09-11
          • 2013-02-11
          相关资源
          最近更新 更多