How to center text, if there is item at the right of line

enter image description here

Here is what I want to get.
The black part is the container div. width 100%
The blue part is the main header text div,
And the pink one is the button that should be placed at the right of the container div.

Question: How to center header text, so it will be the center of the container div, not the center of the blue part? My problem is when I give the pink button position: absolute; that button keeps floating while scrolling.

>Solution :

Maybe something like this:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px solid darkgrey;
  padding: 1rem;
  margin: 1rem;
  position: relative;

.header__title {
  text-align: center;
  background-color: lightgreen;

.header__button {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
<header class="header">
  <h3 class="header__title">Header text here</h3>
  <button class="header__button">Button</button>

Of course you can change the background colors, border, padding, margins, … to fit your design. This is just to illustrate where the elements are.

The key here was to use position: absolute on the button.

position: absolute remove the element (the button) from the document flow, so the other element (the header text) can be centered on 100% width of the page.

Some good information about position absolute here on MDN

Leave a Reply