本问题已经有最佳答案,请猛点这里访问。
如何在此div中将文本居中(水平和垂直)?
的HTML
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
的CSS
.text {
width:150px;
background:red;
float:left;
height:150px;
margin:10px;
text-align:center;
word-wrap:break-word;
overflow:hidden;
color:white;
}
这应该可以回答您的问题。
这里是完整的解释。读这个。
如果要垂直和水平居中到未知高度,宽度元素。您必须将父样式添加为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
}
您能告诉我为什么不使用text-align:center吗?
文本对齐:居中仅适用于水平。 但是如果要垂直居中对齐。 您必须将样式作为display:table-cell添加到元素。 垂直对齐仅适用于display:table-cell。 而Display:table-cell只在display:table内部工作;
有关代码笔的示例:http://codepen.io/anon/pen/BFqfx/
div {
width:150px;
height:150px;
line-height: 150px;
background:red;
color: #fff;
}
div p {
display: inline-block;
vertical-align: middle;
line-height: normal;
width: 100%;
text-align: center;
}
屏幕截图
div内的html正文中的p标签在哪里?
那我的float:left; word-wrap:break-word; overflow:hidden;呢?
为了简单起见,Ive刚刚删除。 添加您想要的所有样式
您的代码确实可以在CodePen中使用,但是不能在我的IE / Chrome中使用,文本未对齐水平/垂直。
这是所有样式为codepen.io/anon/pen/iupys的codepen,在Chrome上仍然可以正常使用
还有另一种常见的技术,基于"绝对定位"和负的上边距。
HTML:
Unknown stuff to be centered.
CSS:
.foo{
width:150px;
height:150px;
background:red;
position:relative;
}
.bar {
text-align: center;
position:absolute;
top:50%;
height:40px;
margin-top:-20px;
border:solid 1px blue;
}
这个想法是,您从内部div的顶部向下移至50%,然后将其向上推一半高度,负上边缘为顶部。
非常稳定且跨平台,唯一的限制是您必须知道内部div的高度。
为避免这种成本浪费,一种解决方法是将负数margin-top替换为transform: translateY(-50%);。在这种情况下,通过CSS转换可以直观地获得对中心DIV的负平移。
之所以有用,是因为您可以在不知道内部DIV高度的情况下使用它,但是请记住,转换是从DOM渲染中提取的。
我希望div的高度最大为150 * 150
好的....您可以简单地将内部div的宽度和高度设置为150px,然后将更大的宽度和高度应用于容器。 原理是一样的。
演示
的HTML
Unknown stuff to be centered.
的CSS
.foo{
display: table;
width: 100%;
}
.bar {
display: table-cell;
text-align: center;
vertical-align: middle;
}
文章