ub_303
ub_303

Reputation: 330

How to make h1 tag center with its actual width

I need to make h1 tag center and also need to make a border around it. To prevent taking up more width I give display: inline-block but the tag does not respond to text-align: center then.

h1 {
  text-align: center;
  border: 1px solid;
  display: inline-block;
}
<div class="container">
  <h1>This is the Title</h1>
</div>

Upvotes: 5

Views: 4401

Answers (7)

gavgrif
gavgrif

Reputation: 15499

I agree with @j10i2 - .container{text-align:center;}, but another way to do it is to center content within the h1. The h1 is a block level element - so insert a span into it and place the text within that. Now applying the text-align: center will allow the centering of the span within the h1.

UPDATE - I just noticed that you want a border around the centered content - this is easy - apply the boder to the span that has been centered within the h1.

h1 {
text-align:center;
}

h1 span {
 border: solid 1px #333;
 padding:5px 15px;
}
<h1><span>Heading 1</span></h1>

Upvotes: 0

Elvin Mammadov
Elvin Mammadov

Reputation: 1120

You can use position: absolute; and transform

.heading {
    border: 1px solid black;
    padding: 5px;
    transform: translate(-50%, 0%);
    position: absolute;
    left: 50%;
    top: 0;
}
<h1 class="heading">Heading 1</h1>

Upvotes: 1

Irf92
Irf92

Reputation: 369

Put the following on parent tag instead of h1 tag

text-align: center;

Upvotes: 4

Sanau
Sanau

Reputation: 7

You can follow @gavgrif instructions.

<div class="container">
  <h1><span>Hello</span></h1>
</div>  

h1 {
text-align: center;
}

span {
border: 1px solid #000;
padding: 5px 10px;
}

Upvotes: 1

Shah Zaib
Shah Zaib

Reputation: 25

this would be your HTML.

<div class="heading">
 <h1>My Heading</h1>
</div>

this will go into CSS

.heading {
  text-align: center;
}

.heading h1 {
  border: 1px solid black; 
  display: inline-block;
}

Upvotes: 1

Radiant Ahmed
Radiant Ahmed

Reputation: 191

if you are using bootstrap you can use the class text-center

here is the example what i can understand from your query

HTML:

<div class="head">
  <h1>Game Over</h1>
</div>

css

.head{width:100%;float:left;margin:0 auto;text-align:center;}
 h1{border:1px solid red;text-align:center;position:relative;}
 h1:after{position:absolute;content:"";top:0;width:200px;height:38px;border:1p    x solid green;left:50%;transform:translate(-50%, 0);}

here is the fiddle

Upvotes: 0

Mohammad Usman
Mohammad Usman

Reputation: 39322

You can use display: table on heading. This will make heading to have width depending on its content while it will remain a block level element as well. And you can center it using margin: 0 auto property.

.heading {
  border: 1px solid black;
  display: table;
  margin: 0 auto;
  padding: 5px;
}
<h1 class="heading">Heading 1</h1>

Upvotes: 5

Related Questions