-1

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.

3

1 Answer 1

1

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>
</header>

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

2
  • @R_M i have update the unswer, there was a typo
    – Boguz
    Nov 23, 2022 at 14:16
  • Yess, after the update it works, thanks a lot !
    – R_M
    Nov 23, 2022 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.