Thymeleaf实现图片与两行文本左右并排布局求助
Hey there! Let's get that image and text side-by-side instead of stacked. The issue here is that by default, elements like <img> and <p> are block-level, meaning they take up the full width of their container and stack vertically. Here are two simple, reliable fixes using Thymeleaf (which plays nice with standard HTML/CSS layout techniques):
This is the most flexible approach that works with any project setup. Wrap your image and text in a container div, then use flexbox to align them horizontally.
Thymeleaf Template Code
<div class="image-text-wrapper"> <!-- Thymeleaf image source with @{} for context-relative URL --> <img th:src="@{/images/your-image.png}" alt="Product preview" class="aligned-image"> <div class="text-block"> <p>First line of your descriptive text</p> <p>Second line supporting the first</p> </div> </div>
Add This CSS
.image-text-wrapper { display: flex; align-items: center; /* Vertically centers text with the image */ gap: 1.5rem; /* Adds space between image and text - adjust as needed */ margin: 1rem 0; /* Optional: Add margin around the whole block */ } .aligned-image { max-width: 120px; /* Control image size - set to your preference */ height: auto; /* Preserve image aspect ratio */ } .text-block p { margin: 0.3rem 0; /* Adjust spacing between the two text lines */ }
If your Spring Boot + Thymeleaf project uses Bootstrap, its grid system makes this layout trivial. Use row and col classes to place the image and text in the same horizontal row:
Thymeleaf Template Code
<div class="row align-items-center mb-3"> <div class="col-auto"> <img th:src="@{/images/your-image.png}" alt="Product preview" style="max-width:120px; height:auto;"> </div> <div class="col"> <p>First line of your descriptive text</p> <p>Second line supporting the first</p> </div> </div>
Quick Notes
- The
align-items-centerclass ensures the text is vertically aligned with the image. col-automakes the image column only take as much width as needed, whilecollets the text fill the remaining space.
Either of these solutions will fix your stacked layout issue. Just adjust the sizes, spacing, and styling to match your project's design!
内容的提问来源于stack exchange,提问作者Hello Singh

