简体   繁体   English

将div中的嵌入式块垂直对齐并固定高度

[英]Vertically align an inline-block in a div with a fixed height

CodePen 密码笔

I want to align the both vertically and horizontally, the height and width of the container will be fixed regarding other extenal factors. 我要垂直和水平对齐,容器的高度和宽度将因其他因素而固定。

How do i do that? 我怎么做?

I've tried using flex 我试过使用flex

display: flex;
justify-content: center;
flex-direction: column;

but it gets rid of my horizontal alignment 但是它摆脱了我的水平对齐方式

Actually, there are multiple ways to achieve vertical alignment, here is one: 实际上,有多种 方法可以实现垂直对齐,这是一种:

 div { width: 300px; height: 150px; background-color: #ddd; text-align: center; font-size: 0; } div::before { content: ""; display: inline-block; height: 100%; vertical-align: middle; } a { width: 100px; height:50px; background-color: #ff0000; display: inline-block; vertical-align: middle; font-size: 16px } 
 <div> <a href="#">Some Text</a> </div> 

Found the solution! 找到了解决方案!

On the div parent: 在div父对象上:

position:relative;

On the a child: 在一个孩子上:

position: absolute;
top: 50%;
left: 50%;
margin-left: -half_its_width;
margin-top: -half_his_height;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM