Web R
Web R

Reputation: 575

Center text vertically and horizontally without absolute positioning

First of all, it's different from others questions because I can't use position: absolute; as I used usually because of my jQuery plugin (I don't use this plugin in the example, but I have to do position: relative; to the inside-table).

JSFIDDLE: https://jsfiddle.net/h8ywumbk/

HTML:

<div id="table">
  <div id="inside-table" >
    <span>Hello</span>
  </div>
</div>

CSS:

#table {
  width: 100%;
  height: 100px;
  border: solid 1px black;
  background-color: transparent;
}
#inside-table {
  position: relative;
  width: 98%;
  height: 80px;
  background-color: transparent;
  border: solid 1px black;
  margin: 0 auto;
  margin-top: 10px;
}
#inside-table span {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

I'm trying to center the text (not a single line) vertically and horizontally on the tables. Any suggestions?

Upvotes: 0

Views: 685

Answers (3)

cfatt10
cfatt10

Reputation: 788

I got it centered like this:

#inside-table span {
  position: relative;
  top: 50%;
  left: 50%;
}

You can always mess with the percentages if you want it shifted one direction or another

Upvotes: 0

Roman Hutnyk
Roman Hutnyk

Reputation: 1549

Try this:

.table {
  display: table;
  width: 100%;
}
.td {
  display: table-cell;
  vertical-align: middle;
}

<div class="table">
  <div class="td">
    text
  </div>
  <div class="td">
    <img alt="" src="http://url style="width: 120px; height: 148px;" />
  </div>
</div>

Upvotes: 0

Narek-T
Narek-T

Reputation: 1928

Just use flexbox

#table {
  width: 100%;
  height: 100px;
  border: solid 1px black;
  background-color: transparent;
}
#inside-table {
  position: relative;
  width: 98%;
  height: 80px;
  background-color: transparent;
  border: solid 1px black;
  margin: 0 auto;
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
#inside-table span {
  
}
<div id="table">
  <div id="inside-table">
    <span>Hello</span>
  </div>
</div>

Upvotes: 2

Related Questions