如何修复代码以使CSS完全居中

时间:2016-06-19 11:44:24

标签: html css css3 cover

早上好,我目前正在研究投资组合,我正在尝试使我的封面元素完全垂直和水平居中。我已设法使用margin: 0 autodisplay: table-cellvertical-align执行此操作,出于某种原因,当我添加CSS3三角形时,它开始将我的徽标向左推。有什么技巧可以解决这个问题吗?



.cover {
  background-size: cover;
  background-color: white;
  display: table;
  width: 100%;
  padding: 0 20%;
  height: 1900px;
}
.logo-container {
  margin: 0 auto;
  background-size: cover;
  height: auto;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  padding-top: 40px;
  padding-bottom: 40px;
}
#triangle-bottomright {
  width: 0;
  height: 0;
  border-bottom: 100px solid #84cfc5;
  border-left: 100px solid transparent;
  padding-top: 1500px;
  margin-left: 850px;
  margin: 0 auto;
}
#triangle-topright {
  width: 0;
  height: 0;
  border-top: 100px solid #84cfc5;
  border-right: 100px solid transparent;
  margin-right: 1000px;
  margin-left: -200px;
  position: relative;
  left: -1000px;
  right: -1000px;
  top: 150px;
}

<div class="cover">
  <div class="logo-container">
    <img class="logo" src="images/personal-logo.png" alt="logo-brand" />
  </div>
  <div id="triangle-topright"></div>
  <div id="triangle-bottomright"></div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

三角形导致移位,因为它们占用了页面流中的空间。您应该使用position:absolute来定位它们,以使它们脱离页面流,并在父position:relative div上设置.cover。示例如下。

&#13;
&#13;
html, body {
  height: 100%;
  margin: 0;
}
.cover {
  background-color: white;
  display: table;
  width: 100%;
  height: 100%;
  position: relative;
}
.logo-container {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
#triangle-bottomright {
  width: 0;
  height: 0;
  border-bottom: 100px solid #84cfc5;
  border-left: 100px solid transparent;
  position: absolute;
  bottom: 0;
  right: 0;
}
#triangle-topright {
  width: 0;
  height: 0;
  border-top: 100px solid #84cfc5;
  border-right: 100px solid transparent;
  position: absolute;
  left: 0;
  top: 0;
}
&#13;
<div class="cover">
  <div class="logo-container">
    <img class="logo" src="http://placehold.it/240x80" alt="logo-brand" />
  </div>
  <div id="triangle-topright"></div>
  <div id="triangle-bottomright"></div>
</div>
&#13;
&#13;
&#13;