Unable to center h1 after adding a second element using display: inline;

Viewed 78

In my current application (photo below), I am trying to add a button to navigate back. But the button needs to be on the line as the h1. The problem is, after adding the button, my CSS property for the h1 text-align: center moves to the right, because of the new button I added.

enter image description here

What can I do to make the h1 centered again?

.backButton {
  margin-top: 40px;
  float: left;
  margin-left: 25%;
}

.titleAndBackButton {
  width: 100%;
  display: inline;
  margin-top: 40px;
}

h1 {
  margin-top: 40px;
  display: block;
  text-align: center;
}
<div class="titleAndBackButton">
  <button pButton type="button" icon="pi pi-arrow-left" class="p-button-outlined backButton"></button>
  <h1>Edit Your Category</h1>
</div>

I am very grateful for every help offered!

2 Answers

This is a crude solution based on your code, and I advise using flex, grid or absolute positioning.

You use margin-left: 25% for a .backButton selector. For this reason, the h1 tag is discarded. Use rule left in conjunction with rule position: relative. Remove margin-left: 25%, and add these css rules to the .backButton selector:

position: relative;
left: 25%;

Use rules left, position: relative and transform: translateX(50%) for tag h1 using rule float: right. Add these rules to tag h1:

float: right;
position: relative;
left: -50%;
transform: translateX(50%);

.titleAndBackButton {
    width: 100%;
    display: inline;
    margin-top: 40px;
}

.backButton {
    margin-top: 40px;
    float: left;
    position: relative;
    left: 25%;
}

h1 {
    margin-top: 40px;
    display: block;
    text-align: center;
    float: right;
    position: relative;
    left: -50%;
    transform: translateX(50%);
}
<div class="titleAndBackButton">
    <button pButton type="button" icon="pi pi-arrow-left" class="p-button-outlined backButton"></button>
    <h1>Edit Your Category</h1>
</div>

you can use {position: absolute} and then center it

Related