Bootstrap网格中<a>标签换行问题:如何实现标签与链接同行?
问题分析
你遇到的换行问题,根源是嵌套的row容器中,包裹<a>标签的<div>没有添加Bootstrap的列(col-*)类。Bootstrap的row是flex布局,但未添加列类的子元素会默认占据整行宽度,导致和前面的标签容器换行显示。
解决方法
方式一:给链接容器添加列类(贴合Bootstrap网格规范)
给包裹<a>的<div>补充对应的col-*类,让它和标签容器的列宽总和为12,就能实现同行显示:
<div class="row"> <!-- Start mother and father row --> <div class="mb-2 col-lg-6"> <div class="row"> <div class="text-md-end text-muted col-md-2 col-lg-4"> Mother </div> <!-- 添加对应列类,与标签容器列宽总和为12 --> <div class="col-md-10 col-lg-8"> <a *ngIf="horse.mother" [routerLink]="['/horses', horse.mother.id, 'detail']" > {{horse.mother.name}} </a> </div> </div> </div> <div class="mb-2 col-lg-6"> <div class="row"> <div class="text-md-end text-muted col-md-2 col-lg-4"> Father </div> <!-- 添加对应列类,与标签容器列宽总和为12 --> <div class="col-md-10 col-lg-8"> <a *ngIf="horse.father" [routerLink]="['/horses', horse.father.id, 'detail']" > {{horse.father.name}} </a> </div> </div> </div> <!-- End mother and father row --> </div>
方式二:使用flex布局替代内部row(更灵活)
如果不需要严格的网格列宽,可将内部的row替换为d-flex align-items-center,直接让标签和链接在一行垂直居中对齐:
<div class="row"> <!-- Start mother and father row --> <div class="mb-2 col-lg-6"> <!-- 替换row为flex布局类 --> <div class="d-flex align-items-center"> <div class="text-md-end text-muted me-2"> Mother </div> <div> <a *ngIf="horse.mother" [routerLink]="['/horses', horse.mother.id, 'detail']" > {{horse.mother.name}} </a> </div> </div> </div> <div class="mb-2 col-lg-6"> <!-- 替换row为flex布局类 --> <div class="d-flex align-items-center"> <div class="text-md-end text-muted me-2"> Father </div> <div> <a *ngIf="horse.father" [routerLink]="['/horses', horse.father.id, 'detail']" > {{horse.father.name}} </a> </div> </div> </div> <!-- End mother and father row --> </div>
内容的提问来源于stack exchange,提问作者Nikola
相关产品推荐
相关产品推荐

