简体   繁体   中英

text align:center is not doing well with width and display: inline-block

I am trying to have my text centered with a costum width. Setting the width or max width will restore the position of the line to left. I am doing it like this:

HTML file

CSS file

Result

I need to have custom width for each of them, have <h6> and <a> in one line and all of the content (including the border) in the middle.

You need to set the parent of the h1 to text-align:center

 body { text-align: center; } h1 { background: lightgreen; font-family: sans-serif; width: 200px; display: inline-block; } 
 <h1>Some text</h1> 

 /*without display: inline-block;*/ .h1{ text-align: center !important; font-family: sans-serif; width: 200px; margin: auto; } /*with display: inline-block;*/ .with_div{ text-align: center; } .with_div h1{ text-align: center !important; font-family: sans-serif; width: 200px; display: inline-block; } 
 <!-- without display: inline-block; --> <h1 class="h1">hello</h1> <!-- with display: inline-block --> <div class="with_div"> <h1>hello</h1> </div> 

You can achieve this, regardless of whether it is in div or not with the CSS below. Similar to some of the others, but it also includes margin: auto; which will center the h1 even if it is displayed as inline or inline-block.

body{
  text-align: center;
}
h1{
  text-align: center !important;
  font-family: sans-serif;
  width: 200px;
  margin: auto;
  display: inline-block;
}

Without any wrapper div. CSS flex

h1{
  display:flex;
  justify-content:center;
}

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