如何垂直设置div中心

时间:2018-12-18 12:18:01

标签: html css

我正在尝试使用下面的代码垂直对齐div元素的中心,但是由于很长一段时间我一直试图获取它,但是没有结果可以帮助我,请问我在哪里做我的堆栈以及如何做

.center {
    padding: 10px 0;
    border: 3px solid green;
    margin-left:10px;
    margin-right:10px;
  }
 
<!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    
    <h2>Center Vertically</h2>
    <p>In this example, we use the padding property to center the div element vertically:</p>
    
    <div class="center">
      <p>I am vertically centered.</p>
      <form action="/action_page.php">
      <fieldset>
        <legend>Personal information:</legend>
        First name:<br>
        <input type="text" name="firstname" value="Mickey"><br>
        Last name:<br>
        <input type="text" name="lastname" value="Mouse"><br><br>
        <input type="submit" value="Submit">
      </fieldset>
    </form>
    </div>
    
    </body>
    </html>

解决这个问题?

https://www.w3schools.com/code/tryit.asp?filename=FYB6T0NY6DTE

1 个答案:

答案 0 :(得分:0)

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .center {
      position: relative;
      padding: 10px 0;
      border: 3px solid green;
      top: 50%;
      transform: translateY(-50%);
    }
    </style>
    </head>
    <body>
    
    <h2>Center Vertically</h2>
    <p>In this example, we use the padding property to center the div element vertically:</p>
    
    <div class="center">
      <p>I am vertically centered.</p>
      <form action="/action_page.php">
      <fieldset>
        <legend>Personal information:</legend>
        First name:<br>
        <input type="text" name="firstname" value="Mickey"><br>
        Last name:<br>
        <input type="text" name="lastname" value="Mouse"><br><br>
        <input type="submit" value="Submit">
      </fieldset>
    </form>
    </div>
    
    </body>
    </html>