Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical align span inside div [duplicate]

Tags:

html

css

http://jsfiddle.net/UmHNL/2/

<div class="container">

    <span>Some text, yay</span>

</div>

<div class="container">

    <span>Some text, yay. But shit time, there is alot of text, so we get a problem with breaking lines and the given height :( How can I align vertical now?</span>

</div>
<style>
.container {
    width: 100%;
    height: 50px;
    line-height: 50px;
    border: 1px solid black;
}

.container span {
    padding-left: 30px;
}
</style>

This solution works great until the screen-width is too small - breaking my text into several lines.

When I google the problem I find so many crazy over-complicated solutions with javascript and divs to push my content in place.. Can anyone help me make this work without adding more markup? :)

There's no need to support Internet Explorer and older browsers.

Thanks

like image 877
Johannes Avatar asked Feb 05 '14 12:02

Johannes


People also ask

How do you vertically align a span inside a div?

The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.

How do I center text vertically in a span?

First, the <span> tag sets the height of <div> tag using the line-height property. The <span> also becomes an inline-block with the use of the vertical-align: middle. With <span> now an inline-block, it can be set at middle by using vertical-align: middle which works great for inline-block elements.

Is vertical-align deprecated?

Deprecated as an attribute Occasionally you will see “valign” used on table cells to accomplish vertical alignment. e.g. <td valign=top> . It should be noted that this attribute is deprecated and should not be used.

Can you use text-align with SPAN?

Use a p or div rather than a span. Text is an inline element and so is a span. For text-align to work, it must be used on a block level element (p, div, etc.) to center the inline content.


2 Answers

You should try this:

.container {
    width: 100%;
    height: 50px;
    border: 1px solid black;
    display: table;
    text-align: center;
}

.container span {
    display: table-cell;
    vertical-align: middle;
}
like image 50
osmanz Avatar answered Oct 23 '22 10:10

osmanz


Update you CSS to

.container {
  width: 100%;
  height: 50px;
  display: table-cell;
  border: 1px solid black;
  text-align: center;
  vertical-align: middle;
}

.container span {
}
like image 41
Ishank Gupta Avatar answered Oct 23 '22 10:10

Ishank Gupta