CSS动态垂直对齐<div>中具有固定高度的文本

时间:2017-03-18 09:51:22

标签: html css

我有一个固定的高度<div>,因为我希望所有<div>元素具有相同的高度。我想将<div>内的文本动态地对齐为垂直中心。我是否可以添加任何标签(spanh1等)?

CSS

.mydiv {
  border-radius: 25px;
  color:#c4c6c7;
  font-size:20px;
  text-align:center;
  background-color:white;
  height: 50px;
  width:40%;
  display: inline-block;
  border-style:solid;
  border-color:#c4c6c7;
  margin: 0 auto;
  overflow: hidden;
}

HTML

<div class="mydiv" id="c1" onclick="checkans(this.innerHTML)">choice 1</div>

3 个答案:

答案 0 :(得分:1)

由于您已在元素上定义了高度,因此最简单的方法是将line-height设置为具有相同数量的px

.mydiv {
  border-radius: 25px;
  color:#c4c6c7;
  font-size:20px;
  text-align:center;
  background-color:white;
  height: 50px;
  width:40%;
  display: inline-block;
  border-style:solid;
  border-color:#c4c6c7;
  margin: 0 auto;
  overflow: hidden;
  line-height: 50px;
}
<div class="mydiv" id="c1" onclick="checkans(this.innerHTML)">choice 1</div>

其他解决方案是使用Flexbox并将align-items: center设置为垂直对齐

.mydiv {
  border-radius: 25px;
  color:#c4c6c7;
  font-size:20px;
  background-color:white;
  height: 50px;
  width:40%;
  border-style:solid;
  border-color:#c4c6c7;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="mydiv" id="c1" onclick="checkans(this.innerHTML)">choice 1</div>

答案 1 :(得分:0)

使用display:table-cellvertical-align:middle对内容进行居中对齐。

&#13;
&#13;
.mydiv {
  border-radius: 25px;
  color:#c4c6c7;
  font-size:20px;
  text-align:center;
  background-color:white;
  height: 150px;
  width:40%;
  display: inline-block;
  border-style:solid;
  border-color:#c4c6c7;
  margin: 0 auto;
  overflow: hidden;
  display:table-cell;
  vertical-align:middle
}
&#13;
<div class="mydiv" id="c1" onclick="checkans(this.innerHTML)">choice 1choice 1choice 1choice 1choice 1<br>choice 1choice 1choice 1choice 1choice 1</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

./getEnergyLevels.sh
sed: 1: "’s/ /,/g’": invalid command code ? 
sed: 1: "’s/;//’": invalid command code ?
sed: 1: "’s/,,/,/g’": invalid command code ? 
sed: 1: "’s/,,/,/g’": invalid command code ? 
sed: 1: "’s/,,/,/g’": invalid command code ?
sed: 1: "’s/,,/,/g’": invalid command code ?
sed: 1: "’s/,,/,/g’": invalid command code ?
sed: 1: "’s/,,/,/g’": invalid command code ?
sed: 1: "’s/,,/,/g’": invalid command code ?
sed: 1: "’s/,,/,/g’": invalid command code ?
sed: 1: "’s/,,/,/g’": invalid command code ?
sed: 1: "’s/,,/,/g’": invalid command code ? 
./getEnergyLevels.sh:10: no matches found: *.bac

fiddler链接为https://jsfiddle.net/4mu8b9bL/