如何将文本居中于div的中心

时间:2019-05-10 07:59:00

标签: html css

我正在尝试将html卡的标题放在标题div中,该标题具有“ x”按钮。

我尝试使用margin: 0 auto居中,但是居中于div的剩余/剩余空间内。我想要的是在div的整个长度内居中(真正的中心)。

title center is offset by the button occupying the div space

<div class="timer-card">
  <div class="head">
    <p class="title">Timer title</p>
    <button class="close">X</button>
  </div>
  <div class="body">
    <p class="countdown">0:00</p>
    <div class="footer"><button>Stop</button><button>Play</button><button>Reset</button></div>
  </div>
</div>
.timer-card {
    border-color: grey;
    border-width: 1px;
    border-style: solid;
    width: 200px;
    background-color: grey;
    box-sizing: border-box;
    padding: 10px;
}

.timer-card .head {
    display: flex;
    justify-content: space-between;
}

.timer-card p.title {
    text-align: center;
}

https://codepen.io/anon/pen/PvZqZz

2 个答案:

答案 0 :(得分:1)

  1. position: relative上的.head元素;
  2. position: absolute; right: 0;上的.close元素;
  3. margin: 0 auto;.title元素上。

下面的代码段:

.timer-card {
    border-color: grey;
    border-width: 1px;
    border-style: solid;
    width: 200px;
    background-color: grey;
    box-sizing: border-box;
    padding: 10px;
}

.timer-card .countdown {
    font-size: 40px;
}

.timer-card button.close, .timer-card .title {
    display: inline-block;
}

.timer-card .head {
    display: flex;
    justify-content: space-between;
    position: relative;
}

.timer-card .title {
  margin: 0 auto;
}

.timer-card .close {
  position: absolute;
  right: 0;
}

.timer-card .body p.countdown {
    margin: 0 auto;
    text-align: center;
}

.timer-card .footer {
    padding-top: 15px;
    display: flex;
    justify-content: center;
}

.timer-card p.title {
    text-align: center;
}
<div class="timer-card">
  <div class="head">
    <p class="title">Timer title</p>
    <button class="close">X</button>
  </div>
  <div class="body">
    <p class="countdown">0:00</p>
    <div class="footer"><button>Stop</button><button>Play</button><button>Reset</button></div>
  </div>
</div>

答案 1 :(得分:0)

一个快速的肮脏技巧是将X按钮的一半大小增加到CSS的空白处

.title {
    width: 100%;
    margin-left: 25px;
 }