css - 如何水平和垂直居中对齐div中的文本?

标签 css

<分区>

我们如何才能将此 div 中的文本居中(水平和垂直)?

HTML

<div class="text">   
hello is the the testhello is the the testhello is the the testhello is the the testhello is the the testhello is the the    
testhello is the the tes   
</div>

CSS

.text {
    width:150px; 
    background:red;
    float:left;
    height:150px;
    margin:10px; 
    text-align:center;
    word-wrap:break-word;
    overflow:hidden;
    color:white;
}

最佳答案

这里是完整的解释。读这个。

http://css-tricks.com/centering-in-the-unknown/

如果你想垂直和水平居中到未知的高度,宽度元素。您必须将父级样式添加为 display:table,将子级样式添加为 display:table-cell。

//已更新

如果您知道元素的高度和宽度。

试试这个。

.parent {
  display:block;
  position:relative;
}

.child {
  display:block;
  height:x;
  width:y;
  position:absolute;
  top:50%;
  left:50%;
  margin-top:-x/2; //Half of the height with minus direction
  margin-left:-y/2; //Half of the width with minus direction
}

关于css - 如何水平和垂直居中对齐div中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23012932/

上一篇:html - 表格样式问题

下一篇:javascript - jQuery 多类选择问题

相关文章:

html - 向右浮动 div 元素

internet-explorer - 使用 svg 图像在 Internet Explorer 上保持纵横比

php - 如何在Azure网站中创建html/php网页子目录?

html - next.js 中的 div 高度不是 100%

javascript - DIV 应该只刷新一次

javascript - 如何在不将文本包装在任何标记中的情况下将文本对齐到 div 的底部?

javascript - CSS 过渡不适用于 classList.add

css - 修改Rails的custom.scss.css导致报错

jQuery DataTable 分页问题

css - margin 不起作用?两个元素之间需要空间