John Stimac
John Stimac

Reputation: 5491

how do i align text vertically using CSS?

<div style='height:200px;'>
SOME TEXT
</div>

how do i align "SOME TEXT" at the bottom of the div using CSS without padding?

Upvotes: 3

Views: 1167

Answers (5)

ActiveCodex
ActiveCodex

Reputation: 120

Using flex, supported in most recent browsers

div {
  align-items: center;
  background: red;
  display: flex;
  
  /* Uncomment to align it horizontally */
  /* justify-content: center; */
}
<div style='height:200px;'>
  SOME TEXT
</div>

Upvotes: 0

muthiulhaq
muthiulhaq

Reputation:

# id{
    display:table-cell; 
    vertical-align:bottom;
    }

Upvotes: 0

bucabay
bucabay

Reputation: 5295

TDs can vertically align text with vertical-align, but this does not work on DIVs. It is not considered good style to use tables to vertically align elements.

You cannot vertical-align text within DIVs with CSS. You can only use padding, margin, or absolute and fixed positioning to align an text vertically.

If you use absolute positioning well, you can vertically align the text by vertically aligning a container that the text is in. However, absolutely positioned elements do not take up "space" within their container, which means you have to set a margin or padding to offset that space in the container.

Eg:

HTML:

<div id="container">
  <span id="text">Some text, Some text, Some text, </span>
</div>

CSS:

#id {
  position:relative;
  margin-bottom: 100px;
}

#text {
  position:absolute;
  bottom:0;
  height: 100px;
  overflow:hidden;
}

Upvotes: 0

David Thomas
David Thomas

Reputation: 253506

The absolute easiest way, though not-exactly using your code example, would be:

div {height: 400px;
    width: 50%;
    margin: 0 auto;
    background-color: #ffa;
    position: relative;
    }

div p   {position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    }

html

<div id="container">
<p>SOME TEXT</p>
</div>

Wrap your text in an element, anything from <p>, <span>, <div>...whatever, and position that element at the bottom of its container.

Upvotes: 1

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53606

You can't do it in a simple way, at least not cross browser.
You can use the display: table; vertical-align: center;
You can use JS/ CSS expressions.
You can have another element inside the div, and position it absolute in relation to the div:

<div style='position:relative;'>
    <div style='position: absolute; bottom:0;>
            My Text
    </div>
</div>

But really, as much as I hate to say, Tables is the KISS here (if you need to veritcaly center it).

Upvotes: 0

Related Questions