<style>
  .centered {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f2f2f2;
  }
</style>
<div class='centered'>
  <!-- 这里放置需要居中和背景的内容 -->
</div>
<p>解释:</p>
<ul>
<li>使用 'display: flex;' 将容器设置为弹性布局。</li>
<li>使用 'justify-content: center;' 和 'align-items: center;' 将内容水平和垂直居中。</li>
<li>使用 'background-color: #f2f2f2;' 设置背景颜色。</li>
</ul>
CSS实现元素居中并添加背景颜色

原文地址: http://www.cveoy.top/t/topic/kzkb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录