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

使用Bootstrap 5实现头像文本布局:圆形头像变椭圆问题排查

问题解答:圆形头像变椭圆的修复方案

问题描述

我尝试实现一个圆形头像搭配侧边文本的展示布局,已成功制作出圆形头像,但添加侧边文本后,头像有时会变为椭圆而非圆形,请问我哪里操作出错了?

相关代码

CSS代码

html,
body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}

.red-label {
    color: red;
}

.fs-small {
    font-size: 0.8em;
}

.fs-smaller {
    font-size: 0.5rem;
}

.user-avatar {
    background-repeat: no-repeat;
    background-size: cover;
    background-color: white;
    background-position: center;
    height: 48px;
    width: 48px;
}

.ellipsis-2 {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2; /* number of lines to show */
    line-clamp: 2;
    -webkit-box-orient: vertical;
}

HTML代码

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<div class="accordion-body row g-3">
  <div class="col-sm-3">
    <div class="px-0 d-flex justify-start align-items-top" title="xwalsh">
      <div class="border user-avatar rounded-circle" style="background-image: url('http://localhost:8001/storage/assets/img/user/profile_pic/nopic.jpg')"></div>
      <div class="ms-2">
        <div class="fw-bold">
          <span>xwalsh</span>
          <span> <i class="fa-solid fa-mars color-male" title="Laki-laki" aria-hidden="true"></i><span class="sr-only">Laki-laki</span> </span>
        </div>
        <div class="fs-small fw-bold text-success">
          <span class="me-2"> Sightseeing[ SS ] </span>
        </div>
        <div class="fst-italic fs-small ellipsis-2">Kabupaten Indramayu, Jawa Barat, Indonesia</div>
        <div class="fst-italic fs-small">lilianskiles@example.com</div>
      </div>
    </div>
  </div>
  <!-- 其余用户项省略 -->
  <div class="px-3 pe-4 m-3 text-end">
    <a href="#">Lihat Semua</a>
  </div>
</div>

问题原因

你使用了d-flex align-items-top的Flex布局容器,当侧边文本的总高度超过头像的48px时,Flex布局会自动拉伸头像元素的高度来匹配容器内最高元素的高度,打破了头像原本宽高相等的比例,导致圆形变成椭圆。

修复方法

有两种简单的修复方式,任选其一即可:

方式1:给头像添加Bootstrap类

直接给头像所在的div加上align-self-start类,强制头像保持自身高度,不被Flex布局拉伸:

<div class="border user-avatar rounded-circle align-self-start" style="background-image: url('http://localhost:8001/storage/assets/img/user/profile_pic/nopic.jpg')"></div>

方式2:修改CSS样式

在.user-avatar的CSS规则中添加align-self: start;,全局生效:

.user-avatar {
    background-repeat: no-repeat;
    background-size: cover;
    background-color: white;
    background-position: center;
    height: 48px;
    width: 48px;
    align-self: start; /* 新增这一行 */
}

原理说明

Flex布局中,align-items: flex-start(对应Bootstrap的align-items-top)虽然会让元素顶部对齐,但容器内存在更高元素时,部分场景下仍会触发元素拉伸。通过align-self: start可以单独为头像设置对齐规则,确保它始终保持48x48的宽高比例,维持圆形外观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:55:55