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

Time:11-24

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.

CodePudding user response:

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 >
  <h3 >Header text here</h3>
  <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

  • Related