CSS center any text with left alignment inside fixed size div

时间:2017-07-12 08:14:30

标签: css css3 flexbox center vertical-alignment

I know a lot of methods to center an inner content but neither of them are working with custom size text with left alignment.

The result I want is http://joxi.ru/krDDq9duE6zL0r

Have tried all the known for me methods:

// first attempt
.inner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

// second attempt
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

// third attempt
.wrapper {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

// forth attempt
.wrapper:after {
  content:'';
  display: inline-block;
  vertical-align: middle;
  height: 74px;
}

Here's the code:

.wrapper,
.wrapper2,
.wrapper3,
.wrapper4 {
  position: relative;
  box-sizing: border-box;
  width: 225px;
  height: 74px;
  padding: 0 20px;
  margin: 5px 0;
  background: yellow;
}

.try1 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.try2 {
  position: relative;
  float: left;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.wrapper2 {
  display: flex;
  align-items: center;
  justify-content: center;
}

.wrapper3 {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

.try4 {
  display: inline-block;
  text-align: left;
}

.wrapper4 {
  position: relative;
  white-space: nowrap;
}

.wrapper4:after {
  content: '';
  display: inline-block;
  vertical-align: middle;
  height: 74px;
}

.try5 {
  display: inline-block;
  vertical-align: middle;
  white-space: normal;
}
<p>Tries:</p>
<div class="wrapper">
  <div class="try1">DUE DILIGENCE EXPIRATION</div>
</div>
<div class="wrapper">
  <div class="try2">DUE DILIGENCE EXPIRATION</div>
</div>
<div class="wrapper2">
  <div class="try3">DUE DILIGENCE EXPIRATION</div>
</div>
<div class="wrapper3">
  <div class="try4">DUE DILIGENCE EXPIRATION</div>
</div>
<div class="wrapper4">
  <div class="try5">DUE DILIGENCE EXPIRATION</div>
</div>

<p>I want:</p>
<div class="wrapper">
  <div class="try1">DUE&nbsp;DILIGENCE EXPIRATION</div>
</div>

UPD Please notice, that the text could be any from one letter to multiple rows. So the inner content width is flexible.

2 个答案:

答案 0 :(得分:1)

您可以将width添加到子元素即.try1, .try2,如果是这样,那么可以使用center将子元素与parent div的{​​{1}}对齐下面,

CSS calc() function
.wrapper {
  width: 225px;
  height: 74px;
  padding: 0 20px;
  background: yellow;
  position: relative;
}

.wrapper > .try1 {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: calc(225px - 96px);
}

您甚至可以使用flex进行检查。

答案 1 :(得分:0)

I have updated the fiddle also. I have changed: position: fixed; padding:padding: 0 51px;

.wrapper4 {
  position: fixed;  
  box-sizing: border-box;
  width: 225px;
  height: 74px;
  padding: 0 51px;
  margin: 5px 0;
  background: yellow;
}

See it live here: jsfiddle