简体   繁体   English

如何在div的中间对齐段落?

[英]How to align a paragraph in the middle of the div?

Using a couple of Angular containers I want to align in the middle of the cells the text. 使用几个Angular容器,我想在单元格的中间对齐文本。 Unfortunately the vertical align doesn't work. 不幸的是,垂直对齐不起作用。

Hereby the code: 特此代码:

 main { height: 100%; text-align: center; padding-top: 6%; padding-left: 7%; padding-right: 7%; font-size: 1em; } .vertical-align { height: 100%; } p { position: relative; vertical-align: middle; } 
 <main> <div class="vertical-align"> <p>{{ data.text}}</p> </div> </main> 

Do you have any idea how I could fix this? 您知道我该如何解决吗?

Thank you! 谢谢!

There is a simple example on w3schools on how to center vertically and horizontally using position & transform. w3schools上有一个简单的示例,说明如何使用位置和变换垂直和水平居中。

Here is a working example. 这是一个工作示例。

 .center { height: 100vh; /* 100vh is used for fullscreen, set your div height here instead. */ position: relative; } .center p { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } 
 <main> <div class="center"> <p>test</p> </div> </main> 

Please refer basic html css reference 请参考基本的HTML CSS参考

 .flex-container { display: flex; justify-content: center; align-items: center; height: 100vh; } 
 <!DOCTYPE html> <html> <body> <div class="flex-container"> <p>Content in center</p> </div> </body> </html> 

https://codepen.io/samuveljohns/pen/JjPWEVz https://codepen.io/samuveljohns/pen/JjPWEVz

Vertical align doesn't work with block elements. 垂直对齐不适用于图块元素。 p tag is a block element p标签是一个块元素

In order to center vertically you need to use flexbox 为了垂直居中,您需要使用flexbox

.vertical-align {
  height: 100%;
  display:flex;
  align-items:center;
}

Refer example below, Also not that I changed the height of the main container from 100% to 100vh just for the sake of the example 请参考下面的示例,同样不是为了示例而将主容器的高度从100%更改为100vh

 main { height: 100vh;/*for example purpose*/ text-align: center; padding-top: 6%; padding-left: 7%; padding-right: 7%; font-size: 1em; } .vertical-align { height: 100%; display:flex; align-items:center; border:1px solid red;/*for example purpose*/ } p { position: relative; /*vertical-align: middle;*/ } 
 <main> <div class="vertical-align"> <p>lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem </p> </div> </main> 

Use text-align center to center your paragraph 使用文本对齐中心将段落居中

.center p
{
     text-align: center;
}

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

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