【问题标题】:How to vertically center a div within a div that changes height based on window size如何在根据窗口大小改变高度的 div 中垂直居中 div
【发布时间】:2016-05-31 13:26:36
【问题描述】:

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 的大小将品牌文本垂直居中。

【问题讨论】:

    标签: html css center


    【解决方案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.

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:
        1. 您需要将 .slogan 设置为位置:relative。
        2. 您只需将 .brand 更改为 position: absolute 并为其设置位置。

        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>

        【讨论】:

        • 我确信它在响应时总是垂直的 .slogan
        猜你喜欢
        • 2012-12-16
        • 2014-05-26
        • 2013-06-24
        • 1970-01-01
        • 1970-01-01
        • 2010-09-08
        • 2013-06-15
        • 2012-06-09
        • 1970-01-01
        相关资源
        最近更新 更多