响应时在div标签中居中

时间:2019-04-01 06:43:06

标签: html css

我想在网页上显示图像。图像足够长,具有固定的高度。因此,当有人通过减小屏幕尺寸检查响应速度时,应从该div中删除多余的尺寸(正在发生)。

我不知道特定的用语。所以,我将尽力解释。应该从中心点开始显示。如果图像是“ abcdefgh”。假设“ a”,“ b” ...都是网格编号。屏幕大小将为一半时的默认行为是“ abcd”,但我想显示“ cdef”。

我给了溢出:隐藏以删除div中多余的图像。我试过了左边距,右边距都自动。但是,仅当图像小于div大小时才需要。

img {
  display: block;
  margin-left: auto;
  margin-right: auto;
}
<!DOCTYPE html>
<html>
  <body>
    <div style="border:4px solid black; height:200px;overflow:hidden;text-align:center;">
    <img src="https://mdbootstrap.com/img/Photos/Slides/img%20(130).jpg" alt="Paris" style="width:100%;height:200px;">
    </div>
    
  </body>
</html>

4 个答案:

答案 0 :(得分:1)

您可以添加object-fit: cover来“裁剪”图像

答案 1 :(得分:1)

您可以为css中的object-fit: cover用图像设置固定大小。

.wrapper {
  border: 4px solid black;
  height: 200px;
  overflow: hidden;
  text-align: center;
}

.img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 100%;
  object-fit: cover;
}
<div class="wrapper">
  <img class="img" src="https://mdbootstrap.com/img/Photos/Slides/img%20(130).jpg" alt="Paris">
</div>

答案 2 :(得分:1)

我使用了object-fit: cover;,这个有效。

img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  object-fit: cover;
}
<!DOCTYPE html>
<html>
  <body>
    <div style="border:4px solid black; height:200px;overflow:hidden;text-align:center;">
    <img src="https://mdbootstrap.com/img/Photos/Slides/img%20(130).jpg" alt="Paris" style="width:100%;height:200px;">
    </div>
    
  </body>
</html>

答案 3 :(得分:1)

仅适合对象:封面不起作用。它还需要widthheight值。为了获得最佳实践,请赋予height值。请该值不应以百分比(%)为单位。并给出图像宽度:100%和高度:100%。它将起作用。

.parentDiv {
  border: 4px solid black;
  width: 80%;
  height: 250px;
  margin: 0 auto;
}

img {
  display: block;
  object-fit: cover;
  width: 100%;
  height: 100%;
}
<div class="parentDiv">
  <img src="https://mdbootstrap.com/img/Photos/Slides/img%20(130).jpg" alt="Paris"><div>

请检查此链接:jsfiddle