【问题标题】:Maintain aspect ratio and center text inside保持纵横比和居中文本
【发布时间】:2016-02-15 22:58:25
【问题描述】:

我有一个 div 响应。我喜欢它在屏幕变化时的工作方式:它像 img 一样工作,它在宽度和高度之间保持一定比例。问题是里面的文字。我怎样才能使文本居中,水平和垂直?同时,如果文本与 div 的限制之间有一定的距离,那就更好了。请记住:所有这些都在响应式环境中。

查看和玩:http://jsfiddle.net/xkr6v9yh/1/

HTML:

<div id="wrapper">
<div id="small">some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, </div>
</div>

CSS:

#wrapper {
    position: relative;
    margin:0 auto;
}


#small {
    width: 100%;
    padding-bottom: 50%;/* 50% of width of container */

    color: white;
    text-align: center;

    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
    background: blue;
}

【问题讨论】:

  • 1- 水平和垂直居中,2- 屏幕变化时有边距或内边距
  • 您是否正在寻找带有 display:flex 的东西:jsfiddle.net/xkr6v9yh/3?或者 display:table/table-cell 会很容易做到
  • @harry:当屏幕改变时,文本可能是 2,3... 行文本。而且css3还没有很好的浏览器支持
  • 这就是你要找的jsfiddle.net/xkr6v9yh/4
  • @Nrc:即使不支持,这种方法也会支持。文本行数增加。从 IE9 开始支持转换,Microsoft 自己从一月开始放弃对 IE8 的支持。

标签: html css responsive-design


【解决方案1】:

应用表格和表格单元格属性来使文本居中对齐。

#wrapper {
	position: relative;
	margin:0 auto;
	background: red;
    display: table;
    width: 100%;
    height: 250px;
}


#small {
	width: 100%;
  	color: white;
  	text-align: center;
    display: table-cell;
    vertical-align: middle;
  	background: blue;
}
<div id="wrapper">
	<div id="small">some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, </div>
</div>

【讨论】:

  • 桌子解决方案需要特定的高度才能工作。我不能使用它,因为 div 在响应式环境中的行为必须像 img
  • @Nrc 你能给我们你的比例吗?或查看我的答案并设置您的值以设置您寻找的正确比率。
  • div 的行为类似于 img 600pxx 300px。我想这是比例 2:1?
  • @Nrc 好的,这将是 50% 的垂直填充。 vertical % padding 或 margin 以父级的宽度为参考。我用这个值更新了我的答案
【解决方案2】:

作为其他答案,但设置了比率:codepen to play with

#wrapper {
  background: red;
  display: table;
  margin: auto;
  width: 75%;
  /* whatever you want to start with*/
  color: white;
}
#small {
  background: blue;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  padding: 1em;
}
/* set here a basic ratio to the container */

#wrapper:before {
  content: '';
  display: table-cell;
  padding-top: 50%;
}
/* FURTHER ? */

/* give a max-width to content ? */

#small>* {
  max-width: 75%;
  margin: 0.5em auto;
}
<div id="wrapper">
  <div id="small">
    <p>some text, some text, some text, some text, some text, some tex</p>
    <p>some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text, some text</p>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 2016-05-16
    • 2012-08-25
    • 2018-04-02
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2017-08-31
    相关资源
    最近更新 更多