Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically align content to the middle of a div? [duplicate]

Tags:

css

sass

I have a div containing some content. It has a height of 31px and inside it, the button has smaller height.

<div class="headerAndButton">
    <h3 class="h3">
        Click the button to the right
        <button>click me</button>
    </h3>
</div> 

I have another header that does not have a button in it.

<div class="headerAndButton">
    <h3 class="h3">No button here, I only want to have this header have the same vertical alignment, height and margin as the other header</h3>
</div>

I want to vertically align the <h3> text within each div. I have tried to solve the problem with the following SCSS:

.headerAndButton {
  margin-bottom: $space-300;

  h3 {
    min-height: 31px;
    vertical-align: bottom;

    button {
      margin-left: $space
    }
  }
}

The vertical-align property has no visible effect. The text in the without the botton is top aligned. The text in the other is a bit lower. It also becomes top aligned if I remove the button.

How can I make this headers have the same vertical alignment? I am not good at CSS, so maybe there are completely different better ways to solve this.

like image 633
user1283776 Avatar asked Jul 08 '16 09:07

user1283776


People also ask

How do I make div content vertical-align middle?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do I vertically center a div within a div?

Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items.

How do I display the contents of a div in the middle?

For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.


2 Answers

You could use several methods to vertical align an element. For example you could use new display: flex methods:

display: flex;
justify-content: center;
flex-direction: column;

Example

If its no problem to position: absolute your element you could use

position: absolute;
top: 50%;
transform: translate(-50%, -50%);

There is a quite good tutorial from CSS-Tricks, named Centering in CSS: A Complete Guide.

like image 69
Marian Rick Avatar answered Oct 06 '22 17:10

Marian Rick


display: flex;
justify-content: center;
align-items: center;

just apply this CSS code on headerAndButton

like image 41
vik Avatar answered Oct 06 '22 15:10

vik