居中 <div>

Centering a <div>

晚上好,

我正在尝试将 'Contact Details' div 居中。我使用了下面的代码但是在使用 position: fixed 之后它看起来不像是居中的。在使用 position:fixed 时,还有另一种方法可以让它完美居中吗?我想让 div 在上下滚动时居中。任何帮助将不胜感激,谢谢!

.secondary {
 height: 350px;
 width: 400px;
 background-color: #ccc;
 box-shadow: 5px 5px 5px #000;
 margin-top: 200px;
 position: fixed;
 margin-left: 40%;
}
<section class="secondary">
 <h3>Contact Details</h3>
   <ul class="contact-info">
     <li class="phone"><a href="tel:###-###-####">###-###-####</a></li>
  <li class="mail"><a href="mailto:e************@gmail.com"             target="_blank">e************@gmail.com</a></li>
  <li class="twitter"><a href="http://twitter.com/intent/tweet?screen_name=ec#######" target="_blank">@ec*******</a></li>
  <li class="linkedin"><a href="http://linkedin.com/in/e####-######-8a791988" target="_blank">Edwin Castro</a></li>
 </ul>
</section>

由于您为 div 使用固定尺寸而不是使其响应,因此您可以使用:

.secondary {
    height: 350px;
    width: 400px;
    background-color: #ccc;
    box-shadow: 5px 5px 5px #000;
    position: fixed;
    margin-left: -200px;
    margin-top: -175px;
    left: 50%;
    top: 50%;
}

它所做的只是将元素移动到中心,然后使用负边距将其拉回一半 width/height 使其完全居中。

虽然这感觉像是一种过时的方法。如果您确实希望改为响应式,您可以尝试类似的操作:

.secondary {
    height: 350px;
    width: 100%;
    max-width: 400px;
    background-color: #ccc;
    box-shadow: 5px 5px 5px #000;
    position: fixed;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

它可能不会为您提供您正在寻找的精确样式,但它会让您走上正确的道路。

试试这个。将 .secondary 替换为 :)

.secondary {
    background-color: #ccc;
    box-shadow: 5px 5px 5px #000;
    position: absolute;
    top: 50%;
    left: 50%;
    padding: 40px;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}