如何使用CSS实现GIF动图在文字右侧显示的布局效果
核心问题说明
- 当前文字容器和GIF容器是两个独立的同级块级元素,浏览器默认会上下堆叠渲染
- 你写的CSS选择器
.animated.gif匹配的是同时携带animated、gif两个类名的元素,而你的GIF用的是id="animated-gif",对应样式完全没有生效
可直接复用的修改方案
第一步:调整HTML结构,新增共同父容器包裹两个模块
<div class="hero-container"> <div class="content"> <section id="desc"> <h2>正宗汉堡</h2> <hr> <p>只用优质食材制作</p> </section> </div> <div> <img id="animated-gif" src="https://media.giphy.com/media/l0Iy1WEZpJQ6V5SVO/giphy.gif" alt="芝士汉堡动图" /> </div> </div>
第二步:替换原有CSS代码
/* 父容器开启flex布局实现左右排列 */ .hero-container { display: flex; justify-content: space-between; align-items: center; /* 可根据实际需求调整布局参数 */ max-width: 1200px; margin: 0 auto; padding: 2rem; gap: 2rem; } /* 修正选择器匹配GIF元素,保留入场动画 */ #animated-gif { animation: animate 1s forwards; } @keyframes animate { 0% { opacity: 0; transform: scale(.5); } 100% { opacity: 1; /* 如果不需要动图默认缩小一半,可修改为transform: scale(1) */ transform: scale(.5); } } /* 移动端适配:小屏幕下自动改为上下排列 */ @media (max-width: 768px) { .hero-container { flex-direction: column; text-align: center; } }
内容的提问来源于stack exchange,提问作者Amaya
相关产品推荐
相关产品推荐

