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

如何在div中实现图片与h1水平对齐且p标签位于h1下方?

Fixing the Alignment of Image, Heading, and Paragraph

Hey there! Let's get your elements aligned just the way you want—with the image and <h1> side-by-side, and the <p> neatly sitting below the heading. Your current code is close, but we need to tweak the flex layout structure a bit to make this work.

What's Off with the Current Setup?

Right now, your .valign class uses transform-based vertical alignment, but since the parent elements aren't properly configured for flex, it's not behaving as expected. Also, <img>, <h1>, and <p> are all block-level elements by default, so they stack vertically instead of placing the image next to the heading.

Here's the Solution

Let's adjust the CSS and restructure the HTML slightly to leverage Flexbox properly:

Updated CSS

.banner {
  position: relative;
  height: 100vh;
  width: 100vw;
  background: #eee;
  display: flex;
  align-items: center; /* Vertically centers content in the banner */
  justify-content: center; /* Horizontally centers content in the banner */
}

.valign {
  display: flex; /* Turns this into a flex container for side-by-side alignment */
  align-items: center; /* Aligns image and text block vertically */
  gap: 1.5rem; /* Adds space between the image and text—adjust as needed */
}

.text-content {
  display: flex;
  flex-direction: column; /* Makes h1 and p stack vertically */
}

Modified HTML

<div class="row">
  <div class="col-xs-12 col-sm-12 col-md-12">
    <div class="banner">
      <div class="container">
        <div class="valign">
          <img src="img/logo.png" style="height: 150px;width: 150px">
          <!-- Wrap h1 and p in a div to keep them stacked -->
          <div class="text-content">
            <h1>Anirudh Sharma</h1>
            <p>This is my portfolio</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Key Changes Explained

  • .banner adjustments: Adding align-items: center and justify-content: center ensures your entire content block is perfectly centered within the full-viewport banner.
  • .valign as flex container: Turning this into a flex container lets the image and text block sit side-by-side, while align-items: center keeps them vertically aligned to each other.
  • .text-content wrapper: This container uses flex-direction: column to force the <h1> and <p> to stack vertically, so the paragraph stays right below the heading like you want.
  • gap property: This is a clean way to add spacing between the image and text—if you need to support older browsers, you can replace it with margin-right: 1.5rem on the image instead.

This should give you exactly the layout you're aiming for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:40:07