简体   繁体   中英

Can't use display:table; together with text-align: center;

I can't use "text-align: center;" together with "display: table;" it only accepts the "display: table;" and when i delete "display: table;" the text gets centered but i want them both because the "display: table;" keeps the line at the bottom of the text as long as the text is.

This is my css:

h2 {
  margin-top: 70px;
  border-bottom: 2px black solid;
  text-align: center;
  display: table;
}

And this is my html:

<h2><?php echo ucfirst($category[0]['name']); ?></h2>

display:table removes the block behavior of the element so now the width is defined by the content; then you can't see any visual text centered because there is no more space around it to center the element if you want table but centered on the page you can use the auto margins (center the entire element), check this snippet with background to see what is happen:

 h2 { text-align: center; background: tomato; border-bottom: 2px black solid; } .table { display: table; margin: 70px auto 0; } 
 <h2 class="table">My title</h2> <h2>My title</h2> 

This problem occur table width.

table defualt width is content width.

You set table width you want. maybe width:100%

display:table and text-align:center will work together for sure if you mention a width for table. Because by default table will just take width of content inside it. So, you can set a width for your table, Like below:

 h2 { margin-top: 70px; border-bottom: 2px black solid; text-align: center; display: table; min-width: 100px; padding-left: 15px; padding-right: 15px; } 
 <h2>Test text</h2> <h2>Test text Test text Test text</h2> 

I guess your solution should be: Use width but add a condition to check if the variable is empty:

<?php 
if($category[0]['name'] != ''){
 echo "<h2>" . ucfirst($category[0]['name']) . "</h2>";
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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