如何在div中垂直居中div,根据窗口大小更改高度

时间:2016-05-31 13:26:37

标签: html css center

CodePen

<div class="wrapper">
  <div class="logo"></div>
    <div class="slogan">
        <div class="brand">
          <p>Contact us now!</p>
        </div>
    </div>
</div>

<style>
body {
  background-image:url(http://science-all.com/images/landscape/landscape-05.jpg);
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  width: 100%!important;
  padding:0;
  margin:0;
}

.wrapper {
  height:100%;
}

.logo {
  height:250px;
  background-color:aqua;
}

.slogan {
  min-height:200px;
  background-color:transparent;
}

.brand {
  color:aqua;
  font-size:25px;
  text-align:center;
}

</style>

我希望口号div根据窗口大小调整高度(例如,当页面打开时,徽标和标语div适合整个屏幕)。但保持徽标div固定大小。我现在面临的问题是根据div的大小垂直居中品牌文字。

3 个答案:

答案 0 :(得分:1)

您可以将.slogan div显示为flexbox

.slogan {
  display: flex; /* Makes your slogan div flexbox */
  justify-content: center; /* Center the content of that div horizontally */
  align-items: center; /* Center the content of that div vertically */
  min-height:200px;
  background-color:transparent;
}

Updated Codepen

答案 1 :(得分:0)

您可以使用flex-box,这可能是最好的解决方案,或者如果您不想这样做,您可以使用CSS中心黑客:

.slogan {
  position: relative;
}

.brand {
  position:absolute;
  left:50%;
  top:50%;
  transform:translate(-50%, -50%);
  (use vendor prefixes as well)

答案 2 :(得分:-1)

  1. 您需要将.slogan设置为position:relative。
  2. 您只需将.brand更改为position:absolute并为其设置位置。
  3. body {
    background-image:url(http://science-all.com/images/landscape/landscape-05.jpg);
        background-size: cover;
        background-position: center;
      background-attachment: fixed;
    width: 100%!important;#
      padding:0;
      margin:0;}
    
    .wrapper {
      height:100%;
    }
    
    .logo {
      height:250px;
      background-color:aqua;
    }
    
    .slogan {
      min-height:200px;
      position: relative;
    }
    
    .brand {
      color:aqua;
      font-size:25px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    <div class="wrapper">
    <div class="logo"></div>
    <div class="slogan">
      <div class="brand">
      <p> Contact us now!</p></div>
      </div>
    </div>