如何使用Bootstrap在固定高度的div中居中放置图像?

问题描述 投票:0回答:3

我想将其中的图像设为<div>的固定大小。我有这个jsp部分(如果需要更多,我会添加)

<html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
<div class="carousel-inner">
 <div class="carousel-item active">
  <img style="margin-top: 5px; max-width: 350px; max-height: 200px; display:block; margin-left: auto;
 margin-right: auto" src="img/${i.imageURLs.get(0)}" height="200" width="350">
 </div>
 <c:forEach var="img" items="${i.imageURLs}">
  <c:if test="${img != i.imageURLs.get(0)}">
   <div class="carousel-item">
    <img style="margin-top: 5px; max-width: 350px; max-height: 200px; display: block; margin-left: auto;
 margin-right: auto" src="img/${img}" height="200" width="350">
   </div>
  </c:if>
 </c:forEach>
</div>
</body>
</html>

CSS是

img {
    width: auto;
    height: auto;
    margin-bottom: auto;
    margin-top: auto;
}

它是jsp页面的表示,其中包含图像URL集合。问题是高度不正确的图片会使我的div的高度变小,并且所有正方形都变小(至少比例很好)。

[what i want everywhere what I see xd

如何正确设置<img>样式以使其居中,或根据图像的高度动态改变下边距?没有width: auto; height: auto;,就没有必要的结果,因此我应该同时使用<img>和CSS中的两种样式。

html css twitter-bootstrap jsp
3个回答
0
投票

正如chriskirknielsen所说,object-fit: contain并将max-height: 200px设置为height: 200px已经达到了预期的行为。


0
投票

您可以执行此操作。


-1
投票

在图像标签上,将对齐方式添加为居中位置

<img style="margin-top: 5px; **align: center;** max-width: 350px; max-height: 200px; display:block; margin-left: auto;
     margin-right: auto" src="img/${i.imageURLs.get(0)}" height="200" width="350" >
© www.soinside.com 2019 - 2024. All rights reserved.