html - 将图像居中并在其下方放置一个 div

标签 html css

我有两个问题。本质上,我想以其原始大小显示图像并将其放置在屏幕中间(中间我的意思是在“水平”中间而不是屏幕的中心),然后在其正下方放置一个带有文本的 div图像。这是我使用的代码:

<div class="figure">;
<img src="...">;
</div>';
<div class="text">
text here
</div>

这是CSS:

.figure{
position:absolute;
margin:0 auto;
left:0;
right:0;
bottom:10px;
top:30px;
}

.figure img{
    margin-left: auto;
    margin-right: auto;
    display: block;
    height:100%;
    width:100%;
}

我有两个问题。第一个是当图像高度理论上长于屏幕高度时,没有垂直滚动条,图像只是调整大小以适应屏幕。第二个问题是在不知道图片大小的情况下如何将文字放在图片下方?我试过 figcaption 但它不起作用。

最佳答案

要使其完美居中,您可能需要 min-height: 100vh;min-width: 100vw; 然后使用 display flex 使其居中。否则,您可能无法将其垂直居中。

此外,将您的文本 block 移动到带有 img 的一个 div 中。

默认情况下,除非您指定,否则 img 不会调整大小。

默认 div 有显示 block ,所以它会占据整行,使用 text-align: center; 它只会让你的文本居中。

.figure {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  min-width: 100vw;
}

.centered {
  text-align: center;
}

html,
body {
  padding: 0;
  margin: 0;
}
<div class="figure">
  <div>
    <img src="http://placehold.it/950x450">
    <div class="centered">
      text here
    </div>
  </div>
</div>

关于html - 将图像居中并在其下方放置一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43959340/

相关文章:

css - 如何固定背景图片的位置?

c# - 使用 XPATH 或 CSS 选择器在 Selenium 中查找元素

html - 水平调整大小时样式困惑

javascript - 了解如何更改 SVG

javascript - 动态生成的费用总和

html - 清除 :both used 时 margin-top 不工作

html - 在 Reaction 创建的网格中对齐文本

css - float 元素上方的文本 float 换行

javascript - 是否有可能使网站上的每个单词实例都不会中断?

javascript - 为什么我在触发点击时遇到过多的递归?