Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading