Vertical and Horizontal alignment of text with CSS [duplicate]

戏子无情 提交于 2019-12-01 12:57:43

You can change just your CSS to this (no HTML changes):

div{
  background: red;
  bottom: 0;
  height: 100px;
  left: 0;
  margin: auto;
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
  text-align: center;
  line-height: 100px;
}

The text-align is self-explanatory. The line-height forces the text to the center by matching the height of a single line to that of the div. You will have to adjust it to your needs each time.

JSFiddle

Here is a common approach used for vertical/horizontal centering.

BASIC EXAMPLE HERE

div {
    background: red;
    width:100px;
    height: 100px;
    display:table;
}
div > span {
    display:table-cell;
    vertical-align:middle;
    text-align:center;
}

Basically, the parent element's display is changed to table. Add in a child element, in this case a span element to wrap the text. The span should have the properties display:table-cell/vertical-align:middle for vertical centering. Then text-align:center is simply for horizontal centering.

Here is an example using the styling you had.

There are different ways. Here is one:

HTML:

<div>
    <span>magix!</span>
</div>

CSS:

div {
    text-align:center;
    display:table;
}
span { 
    display: table-cell;
    vertical-align:middle;
}

Fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!