MMK
MMK

Reputation: 605

How to vertically align a div in an h2 tag?

Well i want to vertically align three divs, one on the left and one on the right and another one in the middle.

Here is the fiddle: http://jsfiddle.net/MK01/6qxm3n5s/

Here is the html code:

<h2>
    <div></div>
    <div id="Title">My Title</div>
    <div></div>
</h2>

And here is the css code:

h2 div{
    float: left;
    width: 30%
}
h2 div:nth-child(1), h2 div:nth-child(3){
    background-color: #000;
    height: 1px
}
#Title{
    text-align: center
}

I have tried a lot of tricks and techniques but none seem to work.

Thank you, MMK.

Upvotes: 0

Views: 78

Answers (3)

Weafs.py
Weafs.py

Reputation: 22992

Instead of using two extra elements for those lines, you could use :pseudo-elements.

#Title:after,
#Title:before {
  position: absolute;
  content: '';
  background-color: #000;
  height: 1px;
  top: 50%;
  margin-top: -1px;
  left: 0;
  width: 33.3%;
}
#Title:after {
  left: 66.66%;
}
#Title {
  position: relative;
  text-align: center;
  width: 100%;
  background: linear-gradient(90deg, transparent 33.3%, tan 33.3%, tan 66.6%, transparent 66.6%);
}
<h2><div id="Title">My Title</div></h2>


You could set the width of :pseudo-elements to 10%(will add up to 20%) if you want the title to be 80%.

#Title:after,
#Title:before {
  position: absolute;
  content: '';
  background-color: #000;
  height: 1px;
  top: 50%;
  margin-top: -1px;
  left: 0;
  width: 10%;
}
#Title:after {
  left: 90%;
}
#Title {
  position: relative;
  text-align: center;
  width: 100%;
  background: linear-gradient(90deg, transparent 10%, tan 10%, tan 90%, transparent 90%);
}
<h2><div id="Title">My Title</div></h2>

Upvotes: 1

symlink
symlink

Reputation: 12209

The simplest way is to give your two outer divs a margin-top:

h2 div:nth-child(1), h2 div:nth-child(3) { background-color: #000; height: 1px; margin-top: 13px; }

and your h2 tag a margin of 0 so it doesn't offset the three divs.

JSFIDDLE

Upvotes: 0

lolbas
lolbas

Reputation: 794

Do not use floats :( You can do one of the following: - apply display: table to parent and display: table-cell to child elements - apply display:inline for inside-h2 divs

Upvotes: 0

Related Questions