1

I'm trying to center the title of an html card within the header div, which has an "x" button.

I've tried centering using margin: 0 auto but it centers within what is left/remainder space of the div. What i want is to center within the full length of the div (true center).

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

kmlkz
  • 63
  • 5
  • inside .timer-card p.title selector add "width: 100%;" – bruce182 May 10 '19 at 08:03
  • @bruce182 trying that, it still centers at the space remaining, not true center. I guess i'll have to make the 'x' button removed from the page flow? but i'm not sure how. – kmlkz May 10 '19 at 08:07

2 Answers2

1
  1. position: relative on the .head element;
  2. position: absolute; right: 0; on the .close element;
  3. margin: 0 auto; on the .title element.

Code snippet below:

.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>
Andrei
  • 169
  • 1
  • 3
  • 13
  • 1
    yes this is it! make the button not part of the div by `position: absolute`, thanks, and everyone else that chipped in! – kmlkz May 10 '19 at 08:11
0

A quick dirty hack would be to just add half the size of the X button as margin-left on your CSS

.title {
    width: 100%;
    margin-left: 25px;
 }
Alex
  • 878
  • 1
  • 10
  • 25