我有一张图片和下面的图片一些描述文字。我希望图像占用尽可能多的空间以使用div的整个宽度,但不要超过可用空间。如果还有剩余垂直空间,则应保留在底部。
我已经尝试过使用flexbox:
#image{
max-width: 100%;
margin-left: auto;
margin-right: auto;
display: block;
flex-grow: 99;
flex-shrink: 99;
}
#flex-box{
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: stretch;
align-content: center;
text-align: center;
}
<div id="flex-box">
<img id="image" src="https://material.angular.io/assets/img/angular-material-logo.svg">
<h1>A header</h1>
<p>A paragraph</p>
<p>Another paragraph</p>
</div>
问题是:
使用css-grid的另一种尝试是:
#images {
width: 100%;
max-height: 100%;
object-fit: scale-down;
}
#grid {
display: grid;
width: 100%;
height: 100%;
grid-template-rows: 1fr auto auto auto;
text-align: center;
justify-items: center;
}
#image-container {
width: 100%;
}
<div id="grid">
<div id="image-container">
<img id="image" src="https://material.angular.io/assets/img/angular-material-logo.svg">
</div>
<h1>A header</h1>
<p>A parapraph</p>
<p>Another paragraph</p>
</div>
这里的问题是:
要获得这些特性需要什么?
在图像上,您可以使用最大宽度并调整高度:
#image {
max-width: 100%;
max-height: 50vh;
}
最大宽度使图像停止扩展以使其超出其容器,并设置最大高度以使其相应缩放。如果要避免垂直滚动,则VH基于屏幕的高度。
如果使用的是Bootstrap 4,则以下代码可以在不使用任何自定义CSS类的情况下为您提供帮助。全部是使用内置在类中的引导程序,它将自动调整内容。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap -->
<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.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<title>Bootstrap Template</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col border"> <img src="https://material.angular.io/assets/img/angular-material-logo.svg" class="img-fluid">
<h1 class="text-center">A header</h1>
<p class="text-center">A paragraph</p>
<p class="text-center">Another paragraph</p>
</div>
<div class="col border text-center align-self-center">
<h2>AA</h2>
</div>
<div class="col border text-center align-self-center">
<h2>BB</h2>
</div>
</div>
<div class="row">
<div class="col text-center border">
<h2>B</h2>
</div>
<div class="col border text-center align-self-center">
<h2>C</h2>
</div>
</div>
</div>
</body>
</html>