如何使用CSS或JavaScript将带有图标和包装(!)文本的面板居中?

时间:2017-06-29 22:05:02

标签: javascript html css alignment

如果文本恰好换行,是否可以将内容(图标+文本)水平和垂直居中放置?似乎CSS引擎不计算包装文本的可见宽度,而我当前的解决方案不起作用...请查看此https://jsfiddle.net/wabrm1st/

HTML:

  <a href=# class="box">
    <span class="icon"></span>
    <span class="text">How can I center when_it_wrapped?</span>
  </a> 

的CSS:

* { box-sizing: border-box; }
.box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 320px;
    height: 100px;
    text-decoration: none;
    padding: 0 30px;
    border: 1px solid red;
}
.icon {
  height: 40px;
  min-width: 40px;
  background: #edc;
  margin-right: 10px;
}

也许,可以用JavaScript计算包装文本的宽度吗?

1 个答案:

答案 0 :(得分:0)

这是我前面提到的解决方案的快速检查。我会看看我是否可以清理它并在以后使其更加优化。如果您想避免使用flexbox,可以使用position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;。再说一次,我会看看以后是否可以发送给你解决方案。

.container {
  width: 220px;
  height: 100px;
  display: flex;
  margin: 0 auto;
  background: #ccc;
  justify-content: center;
  align-items: center;
}

.box{
    width: 80%;
    text-decoration: none;
    border: 1px solid red;
    display: flex;
    flex-direction: row;
    align-items: center;
}

.icon {
  height: 40%;
  width: 20%;
  float: left;
  background: #000;
  margin-right: 5%;
}

.text {
  text-decoration: none;
  border: 1px solid red;
  text-align: center;
}
<body>
<div class="container">
  <a href="#" class="box">
    <span class="icon"></span>
    <span class="text">How can I center when_it_wrapped?</span>
  </a>
  </div>
</body>