koowalsky koowalsky - 1 month ago 7
CSS Question

centered header with button in the same line

i want to create a CENTERED header with button on right.

i already have something like this:




h1{
text-align : center;
margin-right : 32px;
}

button{
position: absolute;
top: 32px;
right: 32px;
}

<html>
<body>
<div><h1>test</h1><button style="float: right;">test</button></div>
<div style="text-align: center;">text</div>
</body>
</html>





but in this case header isnt centered to full width page.

also, if header is too long it should not cover button..



thank you for reading

Answer

If flexbox is an option, you can center the h1 and position the button to the right:

div {
  display: flex;
  justify-content: center;
  position: relative;
}
h1 {
  text-align: center;
}
button {
  position: absolute;
  right: 0;
}
<div>
  <h1>test</h1>
  <button>test</button>
</div>

Cheers!