CSS响应中的垂直对齐 [英] Vertical alignment in css responsive

查看:54
本文介绍了CSS响应中的垂直对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题可能是一个已回答的问题,听起来可能很愚蠢.我想对齐任何元素,无论是文本,图像还是div都可以垂直居中对齐,并且它也应该在响应屏幕中工作.我确实通过添加带有手动百分比的边距最高值来进行尝试.我想知道是否有一种简单且最佳的方法来使垂直对齐响应.

This question might be an answered one and it may sound silly. I would like to align any element whether it is a text, image or a div to align in the center vertically and it should also work in responsive screens. I did try it by adding margin-top with manual percentages. I would like to know if there is a simple and best way to make the vertical alignment responsive.

我什至在google上进行了一些研究,其中一些建议将容器的显示属性更改为table,将div更改为table单元格,然后将垂直对齐方式用作中间位置.这听起来很简单,但也会影响页面中我不想作为表格显示的其他元素.因此,我正在寻找最佳的替代选择.请帮忙.预先谢谢你:)

I even did some research in google about it, some of them suggested to change the display property of the container to table and the div to table cell and then use the vertical alignment as middle. This sounds simple but it also effects the other elements in the page which I don't want to be as a table. Hence I'm looking for best alternate option. Please help. Thank you in advance :)

.in-middle{
   width:100%;
   margin-top: 25%;
}

<body>
  <div class="in-middle">
    <h1>This should be aligned in the center</h1>
    <p>Paragraph which should also be centered</p>
  </div>
</body>

推荐答案

您可以使用

You can use the following solution, using the tranform property:

.in-middle{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

<div class="in-middle">
  <h1>This should be aligned in the center</h1>
  <p>Paragraph which should also be centered</p>
</div>

不建议使用 margin-top (而不是 transform )将元素垂直居中.

It's not recommended to use margin-top instead of tranform to vertically center elements.

这篇关于CSS响应中的垂直对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆