简体   繁体   English

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

[英]How to center a panel with icon and wrapped(!) text with CSS or JavaScript?

Is it possible to center the content (icon + text) within the container horizontally and vertically, if the text happens to wrap? 如果文本恰好环绕,是否可以将内容(图标+文本)在容器内水平和垂直居中? It seems that CSS engine does not calculate a visible width of the wrapped text and my current solution does not work... Please look at this https://jsfiddle.net/wabrm1st/ 看来CSS引擎无法计算包裹文本的可见宽度,并且我当前的解决方案无法正常工作...请查看此https://jsfiddle.net/wabrm1st/

html: 的HTML:

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

css: 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;
}

Maybe, it is possible to calculate the width of the wrapped text in JavaScript? 也许可以在JavaScript中计算换行文本的宽度?

Here is a quick workup of the solution I mentioned earlier. 这是我前面提到的解决方案的快速总结。 I'll see if I can clean it up and make it more optimal later. 我将查看是否可以清理并在以后使其更优化。 If you want to avoid using flexbox you can use position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; 如果要避免使用flexbox,可以使用position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; . Again, I'll see if I can send you that solution later as well. 再次,我将查看以后是否也可以将该解决方案发送给您。

 .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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM