【问题标题】:Getting div to be exactly center of page [duplicate]让 div 恰好位于页面中心 [重复]
【发布时间】:2023-01-27 01:57:54
【问题描述】:

将 div 居中放置在网页的中心。

这已经被问过一百次了,但我仍然无法找到确切的答案。

我试图将这个 div 恰好放在页面的中心。我已经将 justify-content 和 align-items 设置为居中,但它没有显示预期的结果。我确定我错过了什么,但是什么?

body {
  display: flex;
  justify-content: center;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 5px solid black;
  width: 50vh;
  height: auto;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.buttons {
  display: flex;
  padding: 10px;
  margin-top: 10px;
}
<div class="box">
  <div class="content">
    <h1 class="header">BLACKJACK</h1>
    <p id="message-el" class="message">What to play a round? </p>
    <p id="cards-el" class="cards">Cards:</p>
    <p id="sum-el" class="sum">Sum:</p>
    <div class="buttons">
      <button id="button-start-el" class="button-start">START GAME</button>
      <button id="button-draw-el" class="button-draw">DRAW CARD</button>
      <button id="button-new-el" class="button-new">NEW GAME</button>
    </div>
  </div>
</div>

<script src="/js/javascript.js"></script>
</body>

【问题讨论】:

  • 它看起来居中。什么不居中/预期是什么?
  • 只需将 body 高度添加到 100vh,然后 justify-content: center;并对齐项目:中心;并固定你的盒子宽度,你需要将 .box 宽度设置为 max-content

标签: html css flexbox


【解决方案1】:

body 设置为 100vh 并添加 align-items: center;

body {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 5px solid black;
  width: 50vh;
  height: auto;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.buttons {
  display: flex;
  padding: 10px;
  margin-top: 10px;
}
<body>
<div class="box">
  <div class="content">
    <h1 class="header">BLACKJACK</h1>
    <p id="message-el" class="message">What to play a round? </p>
    <p id="cards-el" class="cards">Cards:</p>
    <p id="sum-el" class="sum">Sum:</p>
    <div class="buttons">
      <button id="button-start-el" class="button-start">START GAME</button>
      <button id="button-draw-el" class="button-draw">DRAW CARD</button>
      <button id="button-new-el" class="button-new">NEW GAME</button>
    </div>
  </div>
</div>

<script src="/js/javascript.js"></script>
</body>

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 2015-01-31
    • 2021-12-08
    • 2012-03-30
    • 2018-01-15
    • 2018-01-06
    • 1970-01-01
    • 2018-09-09
    相关资源
    最近更新 更多