如何在div中实现图片与h1水平对齐且p标签位于h1下方?
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
.banneradjustments: Addingalign-items: centerandjustify-content: centerensures your entire content block is perfectly centered within the full-viewport banner..valignas flex container: Turning this into a flex container lets the image and text block sit side-by-side, whilealign-items: centerkeeps them vertically aligned to each other..text-contentwrapper: This container usesflex-direction: columnto force the<h1>and<p>to stack vertically, so the paragraph stays right below the heading like you want.gapproperty: This is a clean way to add spacing between the image and text—if you need to support older browsers, you can replace it withmargin-right: 1.5remon the image instead.
This should give you exactly the layout you're aiming for!
内容的提问来源于stack exchange,提问作者Anirudh Sharma

