首页 > 解决方案 > 当 p 元素具有设置宽度的背景颜色时,不能居中

问题描述

我在不使用 margin-left 的情况下自动居中 p 元素时遇到了麻烦。body 元素是居中对齐的,但由于 p 元素上有背景颜色,所以它不起作用...

    p {
      background-color: dimGray;
      width:250px;
      margin-left: 630px;
      
    }
    
    h3 {
      margin: 20px;
    }
    
    h1 {
      margin-top: 30px
    }
    
    a {
      color: red;
    }
    
    body {
      background-color: black;
      color: white;
      text-align: center;
      font-family: "Verdana", sans-serif;
    }
    
<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Netflix</title>
      <link rel="stylesheet" href="style/style.css">
    </head>
    <body>
      <img src="https://lh3.googleusercontent.com/proxy/nusBlyscc3HZ_yW7ZSTS3E-Ci8ZZv_ALi1K1eWse3rlX2emUBz_tW0XbCMh9yp_pAnOLN24Ct2OWoBNvH629ziJr9EK_Q3PCB73IwAughUCGA4nZhjN1NvkAIVOq4LGIlw">
    
      <h1>See what´s next</h1>
      <h3>Watch anywhere, but mostly from home</h3>
      <a href="https://mimo.app/r/homeflix.html">Try 30 Days Free</a>
      <p>Watch TV shows and movies</p>
      
      <script src="script.js"></script>
    </body>
    </html>

这是我无法自动居中的灰色框。我似乎无法找到一种方法来做到这一点。

这是我在居中时遇到问题的灰色框

标签: css

解决方案


既然你给了“p”一个特定的宽度,现在你可以给它

p{
   /* your current style */
   margin:auto;
}

具有“display:block”属性的元素,如标题和段落等,如果在给它们特定宽度后添加 margin:auto 可以居中,如果没有固定宽度,它们将占据整个页面宽度


推荐阅读