How to center an HTML element with border that matches width

18,120

Solution 1

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

Solution 2

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;
}
Share:
18,120
kursus
Author by

kursus

Updated on November 24, 2022

Comments

  • kursus
    kursus over 1 year

    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;
    }
    
  • kursus
    kursus almost 11 years
    How do you center the text then ?
  • kursus
    kursus almost 11 years
    Text is not centered this way.
  • Kenneth
    Kenneth almost 11 years
    That is what I meant with the layout behavior. I've edited my answer
  • Jay Na
    Jay Na almost 11 years
    The first one is the answer. Second doesn't center the text
  • Admin
    Admin almost 11 years
    updated the second one to work - auto margins and position relative with display inline centers the text
  • kursus
    kursus almost 11 years
    Solution 1 made the trick, however despite update solution 2 doesn't work, can you provide a working example ? Thanks anyway for the answer.
  • hupsohl
    hupsohl almost 11 years
    Put text-align:center on the div.
  • Admin
    Admin almost 11 years
    Option 2, you'd have to specify a width, I'm realizing, which is something you said you didn't want to have to do... but here's a fiddle anyways jsfiddle.net/9kA9G