spraff
spraff

Reputation: 33445

How can I center text in a container that's too small?

I want to use CSS to create a "+" button. The following nearly works:

<p><span class="a">+</span>Foo</p>
<p><span class="b">+</span>Foo</p>

with

.a
{
  width:3ex;
  height:3ex;
  line-height: 3ex;
}

.b
{
  width: 1ex;
  height: 1ex;
  line-height: 1ex;
}

.a, .b
{
  display:inline-block;
  /*display:table-cell;*/
  background:red;
  text-align:center;
  vertical-align:middle;
  margin: 0 1ex;
}

This renders in Firefox as:

enter image description here

Nearly there. I'd just like it to still center the plus sign in the case that the containing span is too narrow, so that it spills over both sides symmetrically.

Is that possible?

Upvotes: 6

Views: 1602

Answers (4)

Gregory Magarshak
Gregory Magarshak

Reputation: 2207

I believe the solution you are looking for is:

<div style=“position: relative;”>
  <span style=“position: absolute; left: 50%; transform: translate(-50%,0)”>
     blah
   </span>
 </div>

Upvotes: 1

Paulie_D
Paulie_D

Reputation: 115293

Flexbox actually works perfectly here.

span {
  height: 32px;
  width: 32px;
  font-size: 96px;
  border: 1px solid grey; /* demo only */
  display: inline-block;
  margin:32px; /* demo only */
}
span.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}
<span class="flex">+</span>

Upvotes: 4

Rohan Vats
Rohan Vats

Reputation: 86

I'm Not sure how you're planning to change icon sizes for each Plus button. But here is a try.

Using the Same Fiddle

Try it.

.a
{
  width:3ex;
  height:3ex;
  line-height: 3ex;
}

.b
{
  width: 1ex;
  height: 1ex;
  line-height: 1ex;

}
.a:after, .b:after {
    content: '+';
    text-align: center;
    font-size: 0.8em;
    display: inline-block;
    vertical-align: top;
}

.a, .b
{
  display:inline-block;
  background:red;
  text-align:center;
  vertical-align:middle;
  margin: 0 1ex;
}

The HTML

<p><span class="a"></span>Foo</p>
<p><span class="b"></span>Foo</p>

With this. At-least your .b icon with small font-size will be centered.

Upvotes: 0

Francisco Romero
Francisco Romero

Reputation: 13199

I do not know if this is what you are refering to but you can wrap your + inside another span and then use margin: -50%.

.a
{
  width:3ex;
  height:3ex;
  line-height: 3ex;
}

.b
{
  width: 1ex;
  height: 1ex;
  line-height: 1ex;
}

.a, .b
{
  display:inline-block;
  /*display:table-cell;*/
  background:red;
  text-align:center;
  vertical-align:middle;
  margin: 0 1ex;
}

.text{
  margin: -50%;
}
<p><span class="a">+</span>Foo</p>
<p><span class="b"><span class="text">+</span></span>Foo</p>

Upvotes: 0

Related Questions