kursus
kursus

Reputation: 1404

How to center an HTML element with border that matches width

Tricky one, I have an HTML title, with border-top and border-bottom applied on it. Can I center it so that the borders are the same width as the element ? Now I have to miserably use width, which is not at all a good solution.

See here for a demo : http://codepen.io/anon/pen/KIJAh

HTML

<div>
<h3 class="removeMe">All your base</h3>
</div>

CSS

div {
 padding-top: 30px;
 height: 100px;
 width: 300px;
 margin: 0 auto;  
 background-color: Moccasin;
}

h3 {
  text-align: center;
  display: block;
  border-top: 1px solid black;
  border-bottom: 1px solid black; 
  margin: 0 auto;
}

.removeMe {
 width:160px;
}

Upvotes: 1

Views: 20705

Answers (6)

Muddasir Abbas
Muddasir Abbas

Reputation: 1819

This works for me.

.heading__wrap {
  display: table;
  margin: 0 auto;
}

.heading__wrap .heading__title {
  border-bottom: 2px solid #7f4cab;
  padding-bottom: 12px;
  font-size: 36px;
  font-weight: 300;
  line-height: 42px;
  margin-bottom: 50px;
}
<div class="heading__wrap">
  <h2 class="heading__title">Music to Our Ears</h2>
</div>

Upvotes: 0

user571545
user571545

Reputation:

There are two main options I can think of:

1) set h3 to display: inline AND set the parent element to have text-align: center

Upvotes: 3

lotsofcode
lotsofcode

Reputation: 111

If your looking to get the heading to be aligned to the center ...

http://codepen.io/anon/pen/xoFKH

Highlighted the div background to make it obvious :/

Upvotes: 0

AJak
AJak

Reputation: 3873

I would recommend, display:inline, but if that breaks your layout and you don't want to fix it. You might want to give table a try. Its seems to work the way you want it to in your demo. Not 100% sure its still viable css though.

display: table;

Upvotes: 0

Kenneth
Kenneth

Reputation: 28737

You could add display: inline to your h3 selector:

h3 {
  text-align: center;
  display: block;
  border-top: 1px solid black;
  border-bottom: 1px solid black; 
  margin: 0 auto;
  display: inline;
}

This will of course affect the layout behavior.

EDIT OP wants the text centered:

To keep the text centered add text-align: center to the parent:

div {
    padding-top: 30px;
    height: 100px;
    width: 300px;
    margin: 0 auto;  
    background-color: Moccasin;
     text-align: center;
}

Upvotes: 2

hupsohl
hupsohl

Reputation: 46

You can use display:inline-block; on the h3 instead of display:block;

Upvotes: 0

Related Questions