将内容宽度设置为自动等于宽度

时间:2017-05-29 23:28:22

标签: css angularjs responsive-design

问题标题可能更清楚,但是给定一些文本,如果浏览器宽度允许它适合一行,那么我希望它居中,否则,我不希望只有一个单词包装到下一行,我如何确保它将线条断开大致相等的长度?如果有一种CSS唯一的方式是最好的,否则,我想在Angular 2中做...

即:

Desktop:
[Screen Edge]...."Some interesting text is here"....[Screen Edge]

Phone:
[Screen Edge]....."Some interesting"......[Screen Edge]
[Screen Edge]......."text is here"........[Screen Edge]

NOT 
Phone:
[Screen Edge]."Some interesting text is"..[Screen Edge]
[Screen Edge]..........."here"............[Screen Edge]

2 个答案:

答案 0 :(得分:0)

选项1:

使用flexbox

使用flex-wrap: wrap;并将文字换成div,这样当你需要换行时它会在你想要的位置断开。



.centered {
  text-align: center;
  margin: 10vh 15vw;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

<div class="centered">
  <span>Some interesting text is here&nbsp;</span><span>Some interesting text is here&nbsp;</span>
</div>
&#13;
&#13;
&#13;

选项2:

使用text-align: center;将文字置于中心

使用margin: 5px 80px;创建基本保证金

使用&nbsp;不间断空格以确保您的文字不会中断。 (或者您可以使用带有css规则集white-space: nowrap

的span来包装文本

&#13;
&#13;
.centered {
  margin-top: 100px;
  text-align: center;
}
.centered > div {
  text-align: center;
  margin: 10vh 15vw;
}
&#13;
<div class="centered"><div>Some&nbsp;interesting text&nbsp;is&nbsp;here Some&nbsp;interesting text&nbsp;is&nbsp;here</div></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在这里,我希望它有所帮助。您必须将容器设置为text-align:center以使文本居中。如果您想要它是流动的,则将其宽度设置为100%。您也可以添加填充,以便在切换到移动设备时,它不会显示填充。

body {
  text-align: center;
}
body > div {
  width: 100%;
  height: auto;
  text-align: center;
}
body > div > div {
  margin-bottom: 20px;
  text-align: center;
  border: 1px solid black;
  margin: auto;
  padding: 40px;
}
.web {
  width: 400px;
  text-align: center;
  height: 50px;
}
.mobile {
  width: 100px;
  height: 80px;
}

.container {
  width: 100%;
  height: auto;
  text-align: center;
}
<div>
  <div class="web">
      <div class="container">
        <span>Some interesting text here</span>
      </div>
  </div>

  <div class="mobile">
    <div class="container">
        <span>Some interesting text here</span>
      </div>
  </div>
</div>