display table-cell width is not working correctly

Unless I use width in pixels - I can't get the <p> element to be the same width as it's parents.

This is the example of what's going on: http://jsfiddle.net/sYEAn/

example HTML

<body>
  <div class="some-class">
    <div>
      <p>Some text</p>
    </div>
  </div>
</body>

CSS:

.some-class{
    position:relative;
    margin-top:2vmin;
    width:24vw;
    height:24vw;
    background:rgb(0,0,0);
 }

.some-class div{
    position:absolute;
    z-index: 6;
    width:24vw;
    height:24vw;
    top:0;
    right:0;
    bottom:0;
    left:0;
    background:rgba(255, 255, 255, 0.2);
 }

.some-class div p{
    display:table-cell;
    width:24vw;
    height:24vw;
    vertical-align:middle;
    text-align:center;
 }

The basic idea is to have text centered inside the <div>. Horizontal centering works if I ditch the <p> and leave the text just in the <div> (by setting display:table-cell), but then vertical centering does not. If I do like in jsfiddle I provided - then the <p> element doesn't get wide enough to make horizontal centering.

Any ideas?

Upvotes: 0

Views: 591

Answers (2)

Zivko
Zivko

Reputation: 377

You can try

.some-class div p {
  display: block;
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 24vw;
  margin: 0px;
}

but that wont be pritty if you have more then 1 row of text

2nd solution:

.some-class div p{
  position: absolute;
  display:block;
  width: 100%;
  height: 20px;
  top:50%;
  margin-top: -10px;
  text-align:center;
}

That would be better when you have line wrraping but it wont be centered properly with more then 2 lines

Upvotes: 0

KoernerWS
KoernerWS

Reputation: 44

Miss display in .some-class div

.some-class div {
    display: table;
}

Upvotes: 2

Related Questions