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;
}
Author by
kursus
Updated on November 24, 2022Comments
-
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 almost 11 yearsHow do you center the text then ?
-
kursus almost 11 yearsText is not centered this way.
-
Kenneth almost 11 yearsThat is what I meant with the layout behavior. I've edited my answer
-
Jay Na almost 11 yearsThe first one is the answer. Second doesn't center the text
-
Admin almost 11 yearsupdated the second one to work - auto margins and position relative with display inline centers the text
-
kursus almost 11 yearsSolution 1 made the trick, however despite update solution 2 doesn't work, can you provide a working example ? Thanks anyway for the answer.
-
hupsohl almost 11 yearsPut text-align:center on the div.
-
Admin almost 11 yearsOption 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