使用TailwindCSS实现Flexbox布局时文本元素对齐问题求解
问题根源
你当前的代码把h2、p和头像img放在同一个水平Flex容器中,三个元素默认水平排列,加上p元素设置了mt-12,才会出现错位的问题。
解决方法
把h2和p两个文本元素套在一个垂直排列的Flex容器内即可,调整后的代码如下:
<div class="flex items-center gap-3"> {% if picture != "None" %} <img alt="profile picture" src="{{ picture }}" class="rounded object-fit h-20 cursor-not-allowed"> {% else %} <img alt="Repl Stories" src="https://i.ibb.co/pnJswr2/50e5076526fb3d02fda4bce1f8e6e7d7.png" class="cursor-not-allowed object-fit h-20"> {% endif %} <!-- 新增文本包裹容器,垂直排列内部元素 --> <div class="flex flex-col"> <h2 class="font-bold text-xl text-base">selectthegang</h2> <p class="text-gray-700 text-base">Creator of Repl Stories</p> </div> </div>
调整说明
- 外层flex容器新增
items-center让头像和右侧文本整体垂直居中对齐,新增gap-3控制头像和文本的间距,你可以根据需要调整数值 - 新增包裹h2和p的
flex flex-col容器,让两个文本上下排列,天然对齐左边缘 - 移除了原来h2的多余
m-2、p的mt-12、flex-none等冲突样式,你可以根据自己的间距需要给文本加上下边距
内容的提问来源于stack exchange,提问作者selectthegang
相关产品推荐
相关产品推荐

