如何实现轮播图标两侧切换箭头与图标水平居中对齐?
解决轮播图标与切换箭头的垂直居中对齐问题
我来帮你搞定这个对齐问题!核心问题在于当前的布局方式没有让箭头和图标在垂直方向上居中对齐,而且图标用了绝对定位脱离了正常文档流,导致父元素没法正确对齐内部元素。咱们一步步调整就能实现需求:
问题分析
- 你给
.mySlides设置了position: absolute,让图标脱离了文档流,父容器没法感知它的位置,所以箭头只能停留在父容器的顶部。 - 箭头用了
float来左右排列,但这种方式很难和脱离流的图标实现垂直居中。
修改方案(核心调整CSS)
我们改用Flex布局来实现对齐,这是现在处理居中问题最简洁可靠的方式:
修改后的完整CSS代码
/* 重新设置箭头样式:去掉float,用margin控制间距 */ .decrease, .increase { cursor: pointer; margin: 0 20px; /* 调整箭头和图标的间距,可按需修改 */ } /* 给包含箭头和图标的父容器添加Flex布局 */ .col-sm-12.align-self-center { display: flex; align-items: center; /* 垂直方向居中 */ justify-content: center; /* 水平方向居中 */ min-height: 400px; /* 给容器设置最小高度,保证布局稳定,可按需调整 */ } #contenitore { width: 60%; background-color: blue; } img { max-width: 100%; height: auto; } img:hover { width: 310px; height: auto; } /* 移除绝对定位,让图标回到文档流 */ .mySlides { display: block; width: 300px; height: 300px; border-radius: 50%; margin: 0; }
HTML和JavaScript代码保持不变
你的HTML结构和轮播逻辑都是没问题的,不需要修改:
<!-- Icons fontAwesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"> <header class="ricerca"> <div class="container"> <div class="row"> <div class="col-sm-12 align-self-center"> <span class="decrease" onclick="plusDivs(-1)" value="Decrease Value"><i class="fas fa-chevron-circle-left" style="font-size:50px;"></i></span> <div class="w3-tooltip"> <img class="mySlides" shadow-lg p-3 mb-5 src="https://image.flaticon.com/icons/png/512/945/945170.png" "> </div> <span class="increase" onclick="plusDivs(1)" value="Increase Value"><i class="fas fa-chevron-circle-right" style="font-size:50px;"></i></span> </div> </div> </div> </header>
var slideIndex = 1; showDivs(slideIndex); function plusDivs(n) { showDivs(slideIndex += n); } function showDivs(n) { var i; var x = document.getElementsByClassName("mySlides"); if (n > x.length) {slideIndex = 1} if (n < 1) {slideIndex = x.length} for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } x[slideIndex-1].style.display = "block"; }
为什么这么改?
- Flex布局的优势:父容器设置
display: flex后,通过align-items: center可以轻松让所有子元素(箭头+图标)在垂直方向居中,justify-content: center保证水平方向也居中,完美匹配你的需求。 - 移除绝对定位:原来的绝对定位让图标脱离了文档流,父容器无法将它和箭头一起对齐,去掉后图标回到正常流中,就能被Flex布局控制。
- 替换float:在Flex容器中
float属性是无效的,直接用margin控制箭头和图标的间距更灵活可控。
内容的提问来源于stack exchange,提问作者asbarabungi
相关产品推荐
相关产品推荐

