You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将h1水平垂直居中显示在多图网格区域的正上方?

解决方案

方案1:h1在图片组上方非重叠居中(常规布局)

适合标题放在图片流上方、不遮挡图片的场景,无需调整DOM结构,仅修改样式即可:

  • 调整样式代码如下,同时优化原有grid配置适配10张图片的渲染效果:
const StyledHeader = styled.header`
  width: 60%;
  max-width: 1200px;
  margin: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px; /* 自定义调整h1与下方图片组的间距 */

  h1 {
    width: 100%;
    text-align: center; /* 文字水平居中 */
    line-height: 48px; /* 单行文字下行高等于元素高度即可实现垂直居中,数值可自定义 */
    margin: 0; /* 清除浏览器默认边距避免位置偏移 */
  }
`;

const StyledHead = styled.section`
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 替换auto为1fr保证每列宽度均等,布局更整齐 */
  gap: 5px;
  grid-auto-rows: 1fr; /* 自动生成等高新行,适配10张图片分2行展示的需求 */
  width: 100%;
  opacity: 0.7;
  img {
    height: 100%;
    width: 100%;
    object-fit: cover; /* 避免图片拉伸变形 */
  }
`;
  • 该方案下h1会自动对齐下方图片组的水平中线,正好显示在图片组正上方,文字本身也实现了水平、垂直双向居中。

方案2:h1叠加在图片组上方居中(重叠布局)

如果需要标题叠在图片区域顶部居中显示,可以用定位实现:

  • 样式修改如下:
const StyledHeader = styled.header`
  width: 60%;
  max-width: 1200px;
  margin: auto;
  position: relative; /* 父容器添加相对定位作为定位锚点 */
`;

const StyledHead = styled.section`
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 5px;
  grid-auto-rows: 1fr;
  width: 100%;
  opacity: 0.7;
  img {
    height: 100%;
    width: 100%;
    object-fit: cover;
  }
`;

// 单独封装h1的样式,也可以直接写在StyledHeader的样式规则中
const StyledTitle = styled.h1`
  position: absolute;
  top: 8px; /* 自定义调整距离图片组顶部的垂直距离 */
  left: 50%;
  transform: translateX(-50%);
  margin: 0;
  background: rgba(255,255,255,0.8); /* 可选:添加半透背景提高文字可读性 */
  padding: 4px 12px;
  border-radius: 4px;
`;
  • 组件代码同步替换原有h1标签即可:
<StyledHeader>
        <StyledTitle>Sidetittel</StyledTitle>
        {loading ? <p>laster...</p> : null}
        <StyledHead>
          {data.Search?.length > 0
            ? data.Search.slice(0, 10).map((items) => (
                <img key={uuid()} alt="filmplakat" src={items.Poster} />
              ))
            : null}
        </StyledHead>
</StyledHeader>

内容的提问来源于stack exchange,提问作者Tore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:15:03