首页 > 解决方案 > 将文本放置在图库中间,使其具有响应性

问题描述

如何将标题放置在图库顶部,如下图所示。

我正在使用我的主题附带的画廊简码。

我可以使用 position:absolute; 以及顶部和底部值,然后将其与 display:block 居中;和边距:0自动;。然而,当我改变屏幕的大小时,它就变得不正常了。

html是

<div class="gallery-column">
[shortcode goes here]
<h2>Title goes here</h2>
</div>

在此处输入图像描述

标签: cssgallerypositioningresponsivetitle

解决方案


保持元素水平和垂直居中的最简单方法是使用flexbox

您需要的所有父元素是:

  • display: flex将元素视为 flexbox
  • align-items: center用于垂直对齐
  • justify-content: center用于水平对齐
  • 一个固定的height(创建填充) -100vh全屏

这可以在下面看到:

body {
  margin: 0;
}

.gallery-column {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
<div class="gallery-column">
  <div class="centered">
    <h2>Centered Element</h2>
  </div>
</div>

无论屏幕大小如何,相关元素都将保留在页面的确切中心。

在您的情况下,您还需要 az-index以确保元素保持在顶部。
z-index: 1应该足够了。


推荐阅读