Css 如何在浮动div中垂直居中div?
我正在尝试做一些似乎没有被要求的事情。我有一个问题: 我有两个并排的浮动div,左div包含创建父div高度的内容。右div只包含需要在左div创建的任何高度垂直居中的按钮。所以没有已知的尺寸,无论是高度还是宽度 以下是我所拥有的:Css 如何在浮动div中垂直居中div?,css,Css,我正在尝试做一些似乎没有被要求的事情。我有一个问题: 我有两个并排的浮动div,左div包含创建父div高度的内容。右div只包含需要在左div创建的任何高度垂直居中的按钮。所以没有已知的尺寸,无论是高度还是宽度 以下是我所拥有的: <div class="parent"> <div class="line"> <div class="left"> <p>This is some content t
<div class="parent">
<div class="line">
<div class="left">
<p>This is some content to create some height to the div. </p>
<p>This is some content to create some height to the div. </p>
<p>This is some content to create some height to the div. </p>
<p>This is some content to create some height to the div. </p>
<p>This is some content to create some height to the div. </p>
<p>This is some content to create some height to the div. </p>
<p>This is some content to create some height to the div. </p>
</div>
<div class="right">
<button>Center me vertically</button>
</div>
</div>
</div>
我觉得我很接近,我只是错过了一个重要的概念
因此,如何将按钮垂直居中放置在右侧div中?您可以将div的显示设置为表格单元格,而不是浮动div:
.left {
display:table-cell;
width: 50%;
background-color: yellow;
}
.right {
width: 50%;
background-color: red;
height: 100%;
vertical-align: middle;
text-align: center;
display:table-cell;
}
垂直对齐仅适用于内联或内联块图元。它影响到
对齐元素本身,而不是其内容(应用时除外
对表格单元格)将其应用于表格单元格时
影响单元格内容,而不是单元格本身
请在此处阅读更多信息:
您可以将此CSS应用于按钮的内容
button{
position: relative;
top: 50%;
transform: translateY(-50%);
}
如果您喜欢使用mixin,您可以简单地编写一个垂直对齐规则并在整个项目中重用
混合:
@mixin vertical-align($position: relative) {
position: $position;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
CSS:
好的,这是一个艰难的过程。你们都展示了工作示例,但创建它们的方式有两种。一个比另一个更可靠还是更好?手机友好吗?
@mixin vertical-align($position: relative) {
position: $position;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
button {
@include vertical-align();
}