将Bootstrap卡片用作超链接:包裹<a>标签导致样式异常
嘿,我之前也踩过这个坑!当你直接用<a>标签把整个Bootstrap卡片包起来的时候,Bootstrap自带的<a>标签样式会和卡片的样式冲突,导致卡片变样——毕竟a标签默认有文字颜色、下划线,还有行内元素的特性,会打乱卡片的块级布局。给你两个靠谱的解决方案:
方法一:用Bootstrap自带的
stretched-link类(推荐) 这个方法不用包裹整个卡片,只需要在卡片内部的某个链接上加上stretched-link类,就能让整个卡片区域变成可点击的链接,完美保留卡片样式。这也是Bootstrap官方推荐的实现方式:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <div class="card" style="width: 15rem; display: inline-block"> <img class="card-img-top" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=318×180&w=318&h=180" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card Title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <!-- 加了stretched-link后,整个卡片都会变成可点击区域 --> <a href="#" class="btn btn-primary stretched-link">Go somewhere</a> </div> </div>
原理是stretched-link利用CSS的position: absolute让链接覆盖整个卡片容器,而Bootstrap的.card已经默认设置了position: relative,刚好满足这个类的使用条件。
方法二:强制让
<a>标签继承卡片样式 如果你一定要用<a>包裹整个卡片,那得给<a>加上.card类,同时重置a标签的默认样式,比如去掉下划线、修正文字颜色:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <a href="#" class="card text-decoration-none text-dark" style="width: 15rem; display: inline-block"> <img class="card-img-top" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=318×180&w=318&h=180" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card Title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </a>
这里的text-decoration-none用来去掉a标签默认的下划线,text-dark让文字保持卡片默认的深色(避免a标签默认的蓝色文字),同时给a标签加上.card类,让它拥有卡片的所有样式属性。
内容的提问来源于stack exchange,提问作者Poogy
相关产品推荐
相关产品推荐

