Geographos
Geographos

Reputation: 1486

CSS text not centered properly because of the object location

I want to have my text in the middle. Since I added the element in the same line, the text offsets towards the right.

current result

My code looks like this:

.property {
  background-color: #497ba7;
  color: #ffff;
  text-align: center;
  margin-left: 50px;
  margin-right: 50px;
  padding: 5px;
}

.navbtntop {
  cursor: pointer;
  float: left;
  font-size: 20px;
  background-color: #497ba7;
  color: #fff;
  border-color: rgba(0, 0, 255, 0.082);
  border-radius: 3px;
  text-decoration: none;
  padding: 7px;
  width: 20%;
  text-align: center;
  margin-left: 5.5%;
}
<a href="#" class="navbtntop" onclick="return show('Page1','Page2');">Previous</a>
<h2 class="property">MDU Layout</h2>

Where is the problem then?

Upvotes: 0

Views: 67

Answers (1)

Ezra Siton
Ezra Siton

Reputation: 7771

cols layout

Your idea (Keep the right col "center" to all wrapper area).

One way is by using one "empty" div (20% - 60% - 20%).

The other way is to add margin-right: 20%; for the right col.

.display_grid{
  display: grid;
  border: 2px solid orange;
  grid-template-columns: 20% auto 20%;
}

.left {
  border: 1px solid black;
  display: block;
  background-color: red;
  padding: 20px;
  color: #fff;
  text-align: center;
}

.right {
  background-color: blue;
  color: #ffff;
  text-align: center;
  border: 1px solid red;
  margin: 0px;
}
<div class="display_grid">
  <a href="#" class="left">Left</a>
  <h2 class="right">Right</h2>
  <div>
</div>

position absolute

One more way to achieve this is by position absolute (Old approach - but in your case, if the "left col" width/content change Maybe there is no choice).

Cons: less responsive + the text could overlap.

.relative_wrapper{
  display: grid;
  position: relative;
  border: 2px solid orange;
  grid-template-columns: 20% auto;
}

.left {
  border: 1px solid black;
  display: block;
  background-color: red;
  padding: 20px;
  color: #fff;
  text-align: center;
}

.right {
  background-color: blue;
  color: #ffff;
  text-align: center;
  border: 1px solid red;
  margin: 0px;
  /* position absolute */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="relative_wrapper">
  <a href="#" class="left">Left</a>
  <h2 class="right">Right</h2>
  <div>
</div>

https://medium.com/front-end-weekly/absolute-centering-in-css-ea3a9d0ad72e

Upvotes: 1

Related Questions