如何在React中使用Tailwind CSS居中iframe标签?
如何让嵌套在div中的YouTube iframe居中显示
你当前的问题是只给div加了垂直居中的items-center类,但缺少水平居中的justify-center,而且要确保父div占满可用宽度(比如加w-full),这样flex布局才能生效。另外你写的frameBorder="40%"是错误的,这个属性应该设为0或者直接移除,它是控制边框显示的布尔属性,不能用百分比。
修正后的代码如下:
<div className="flex items-center justify-center w-full"> <iframe width="600" height="400" src="https://www.youtube.com/embed/RB1uDVnhVq0?si=d0DlD-AjqmaPlnEF" title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen> </iframe> </div>
如果不想用flex布局,还有两种简单方法:
- 方法一:给父div加
text-center类,利用行内块元素的特性实现水平居中:<div className="text-center"> <iframe width="600" height="400" src="https://www.youtube.com/embed/RB1uDVnhVq0?si=d0DlD-AjqmaPlnEF" title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen> </iframe> </div> - 方法二:直接给iframe加
mx-auto类(自动左右外边距),同时父div设为w-full:<div className="w-full"> <iframe className="mx-auto" width="600" height="400" src="https://www.youtube.com/embed/RB1uDVnhVq0?si=d0DlD-AjqmaPlnEF" title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen> </iframe> </div>
另外你提到的iframe的align属性确实已经被废弃,不要使用,以上CSS-based的方法是当前标准的实现方式。
内容的提问来源于stack exchange,提问作者devacius the one above all
相关产品推荐
相关产品推荐

