Kirill Bugaev
Kirill Bugaev

Reputation: 390

Place element right vertically centered relative to another element

I have following code snippet

body {
  margin: 0 auto;
  min-width: 480px;
  padding: 0;
  width: 800px;
}

@media (max-width: 840px) {
  body {width: 95%; }
}

div.top-header-cont {
  display: flex;
}

header {
  display: inline-block;
  width: auto;
}

div .theme-select-cont {
  display: inline-block;
  flex-grow: 100;
}

div .theme-select-table-wrapper {
  display: table;
  height: 100%;
  width: 100%;
}

div .theme-select-table-cell-wrapper {
  display: table-cell;
  vertical-align: middle;
}
    <div class="top-header-cont">
        <header>
            <h1>TODO</h1>
        </header>
        <div class="theme-select-cont">
            <div class="theme-select-table-wrapper">
                <div class="theme-select-table-cell-wrapper"><select>
                        <option value="base16-dark">base16-dark</option>
                    </select></div>
            </div>
        </div>
    </div>

It looks like this in browser how code looks in browser I suspect that I can do the same easier, I mean place select element centered vertically relative to h1 element and on right side of page. I don't know how to do it without table wrappers. Or maybe another way, without flexed div elements. Any way my variant looks too mach complex for such easy task like place two element at top of page. What you can suggest to solve this problem? I have seen some solutions using absolute div positioning, but it is not appropriate in my case.

Upvotes: 0

Views: 41

Answers (1)

Kai Qing
Kai Qing

Reputation: 18833

You can use position absolute and transform: translateY(-50%) to vertically center if the 2 elements are bound by the same wrapper with a relative position.

Just make the header position relative, put the select element in there right after the h1 and give it a class to target.

<header>
   <h1>TODO</h1>
   <select class="select-box">
      <option value="base16-dark">base16-dark</option>
   </select>
</header>

header{
  position:relative;
}

.select-box{
    position:absolute;
    top:50%;
    right:2rem;
    transform:translateY(-50%);
}

You may find it easier to balance it the way you have it now. Remember that absolute items don't really know of the surrounding elements so they can overlap if you don't handle your break points correctly.

You can also do this with grid, but until grid is fully supported I'll refrain from providing examples.

Upvotes: 1

Related Questions