繁体   English   中英

将div居中

[英]Centre div inside another

我无法将一个div的内容居中放置在另一个中,因为该内容没有出现。

 #searchbkg { postition: relative; width: 100%; height: 700px; background-color: #85e085; } #searchcentre { position: absolute; width: 50%; margin: 0 auto; } 
 <div id="searchbkg"> <div id="searchcentre">Test</div> </div> 

出现绿色框,但其中没有文本。

您的文字看起来不错,但不会居中,因为您的position: absolute; 在内部div 将其更改为position: relative; 它将水平居中。 如果您需要文本在div中居中,也可以应用text-align: center;

 #searchbkg { position: relative; width: 100%; height: 700px; background-color: #85e085; } #searchcentre { position: relative; width: 50%; margin: 0 auto; text-align: center; border: 1px solid red; } 
 <div id="searchbkg"> <div id="searchcentre">This is a centered div!</div> </div> 

您需要进行以下3项更改才能使内容居中;

  1. 您在#searchbkg样式内的一个CSS属性中有错字。 postition而应该是position
  2. #searchcentre删除position: absolute如果不需要, #searchcentre绝对位置(仅当您要将一个元素放置在另一个元素上时,才应使用绝对位置)。
  3. 添加text-align: center#searchcentre#searchcentre

 #searchbkg{ position: relative; width: 100%; height: 700px; background-color: #85e085; } #searchcentre{ text-align: center; background: orange; width: 50%; margin: 0 auto; } 
 <div id="searchbkg"> <div id="searchcentre">Test</div> </div> 

尝试这个:

 #searchbkg{ postition: relative; width: 100%; height: 700px; background-color: #85e085; text-align:center; } #searchcentre{ display: inline-block; width: 50%; } 
 <div id="searchbkg"> <div id="searchcentre">Test</div> </div> 

暂无
暂无

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

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