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

如何用CSS实现短标题居中、过长时单行显示的图片标题

How to Implement Dynamic Image Title Layout with CSS

Got it, let's walk through exactly how to build this layout: where short titles center neatly above your image, and longer titles stay on a single line (stretching the container to fit their full width) with the image centered below.

Step 1: Basic HTML Structure

First, wrap your title and image in a container so we can control their collective behavior:

<div class="image-container">
  <h3 class="image-title">Short Title</h3>
  <img src="your-image-path.jpg" alt="Your picture description" class="content-image">
</div>

<div class="image-container">
  <h3 class="image-title">This is a much longer title (wider than the picture)</h3>
  <img src="your-image-path.jpg" alt="Your picture description" class="content-image">
</div>

Step 2: CSS Implementation

Here's the code that makes the layout work, with breakdowns for each rule:

.image-container {
  /* Let the container shrink/grow to match its widest child */
  display: inline-block;
  /* Optional: Add spacing around each container */
  margin: 1.5rem 0;
  /* Ensure inline elements (like the title) align center by default */
  text-align: center;
}

.image-title {
  /* Force the title to stay on a single line, no wrapping */
  white-space: nowrap;
  /* Keep title text centered regardless of container width */
  text-align: center;
  /* Optional: Add spacing between title and image */
  margin: 0 0 0.8rem 0;
}

.content-image {
  /* Make the image a block element so margin auto works */
  display: block;
  /* Set your image's fixed width here (replace with your actual image width) */
  width: 220px;
  /* Center the image inside the container when the container is wider than the image */
  margin: 0 auto;
}

How It Works

  • Short title scenario: The inline-block container takes the width of your fixed-size image. The title, with text-align: center, sits perfectly centered above the image.
  • Long title scenario: white-space: nowrap keeps the title on one line, which makes the container stretch to fit the title's full width. The image then uses margin: 0 auto to center itself inside this wider container, while the title stays centered above it.

Optional Tweaks

  • If you want the container to be centered on the page instead of sitting inline, replace display: inline-block with width: fit-content; margin: 1.5rem auto;
  • If your image doesn't have a fixed width, use max-width: 100% on the image instead of a fixed width—this lets it shrink to fit the container when the title is short, and stay at its natural width when the title is long.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:30:26