【问题标题】:Elements won't center on div [duplicate]元素不会以 div 为中心 [重复]
【发布时间】:2021-12-21 01:48:06
【问题描述】:

元素不会以我的 div 为中心,尽管我已经尝试了所有可能的方法(或者至少我决定最终创建一个 Stack Overflow 帐户)方法来修复它
它们以 PC 为中心,但不适用于移动设备。我已经在 CSS 中定义了这个

.page_content {
  background: linear-gradient(90deg, rgba(94, 182, 86, 1) 48%, rgba(121, 230, 111, 1) 100%);
  padding: 20px;
  width: 100%;
  height: 100%;
  text-align: center;
  margin: auto;
  justify-content: center;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  position: fixed;
}
<body style="color: #efefef">
  <div class="page_content">
    <h1>Home page</h1>
    <button class="button" onclick="testFunction()">Example</button>
    <h1>Buttons</h1>
    <button class="button" onclick="testFunction1()">btn 1</button>
    <br>
    <br>
    <button class="button" onclick="testFunction2()">btn 2</button>

  </div>
  </div>
</body>

提前谢谢你

【问题讨论】:

  • 尝试删除padding: 20px;或将其设置为padding: 20px 0;

标签: html css


【解决方案1】:

你可以使用这个 CSS 代码:

* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
}
body {
}
.page_content {
  background: -webkit-gradient(
    linear,
    left top, right top,
    color-stop(48%, rgba(94, 182, 86, 1)),
    to(rgba(121, 230, 111, 1))
  );
  background: -o-linear-gradient(
    left,
    rgba(94, 182, 86, 1) 48%,
    rgba(121, 230, 111, 1) 100%
  );
  background: linear-gradient(
    90deg,
    rgba(94, 182, 86, 1) 48%,
    rgba(121, 230, 111, 1) 100%
  );
  min-height: 100vh;
  display: -ms-grid;
  display: grid;
  place-items: center;
  place-content: center;
  row-gap: 1rem;
}

【讨论】:

    【解决方案2】:

    有两种方法可以解决您的问题。

    方法一 - 移除填充 这些元素没有居中,因为在 css 中有一些填充给 .page-content

    方法 2 - 添加 box-sizing。 如果您需要 div 的填充,则应为父容器添加 box-sizing。根据您给出的代码,其中是正文。此属性包括容器总宽度和高度中的任何填充和边距。

    我在下面的代码中添加了box-sizing:boder-box;

    body{
    box-sizing:border-box; /*ADD THIS*/
    }
    
    .page_content {
       background: linear-gradient(90deg, rgba(94,182,86,1) 48%, rgba(121,230,111,1) 100%);
       padding: 20px;
       width: 100%;
       height: 100%;
       text-align: center;
       margin: auto;
       justify-content: center;
       top: 0; bottom: 0; right: 0; left: 0;
       position: fixed;
    }
    <body style="color: #efefef">
        <div class="page_content">
          <h1>Home page</h1>
          <button class="button" onclick="testFunction()">Example</button>
          <h1>Buttons</h1>
          <button class="button" onclick="testFunction1()">btn 1</button>
          <br>
          <br>
          <button class="button" onclick="testFunction2()">btn 2</button>
    
        </div>
      </div>
    </body>

    【讨论】:

      【解决方案3】:

      您必须删除 .page_content 类中的 padding: 20px;

      【讨论】:

        猜你喜欢
        • 2015-02-16
        • 2013-12-11
        • 1970-01-01
        • 1970-01-01
        • 2011-10-12
        • 2012-10-09
        • 1970-01-01
        • 2018-07-03
        • 1970-01-01
        相关资源
        最近更新 更多