Skip to content
Advertisement

Horizontally center a div relative to the viewport when parent is small

I have a page layout with a sidebar alongside a main-content div. Partway down the page, I have a div (parent) inside of a div (child). The child div needs to be horizontally centered relative to the screen instead of the parent.

<div class="sidebar"></div>
<div class="main-content">
   <div class="parent">
      <div class="child"></div>
      <div class="other-stuff"></div>
   </div> 
</div>

<style>
.parent{
   width: 100px;
}
.child{
   width: 200px;
}
</style>

My first thought was using absolute positioning with something like this:

.child{
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    left: 0;
    right: 0;
    text-align: center;
}

The problem I faced here was that I had to make up for the extra space due to the child being taken out of document flow. “Other-stuff” wanted to move up to fill the gap left behind.

Is there a better way to accomplish this beyond just pushing the div around with absolute positioning and adding extra margin/padding to make up the space so the lower content doesn’t come up?

I’m open to abandoning absolute positioning — that was just the first thing that came to mind.

Advertisement

Answer

You can use a flexbox to position multiple items in one container and knock the children out of the parent div so it’s not affected by whatever positioning you do with that.

*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  width: 100vw;
}

.parent {
  border: 1px solid black;
  width: 100px;
  height: fit-content;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  gap: 2px;
}

.child {
  display: block;
  border: 1px solid black;
  width: 200px;
  height: fit-content;
}

.other-stuff {
  display: block;
  border: 1px solid black;
  width: 200px;
  height: fit-content;
}
<div class="sidebar"></div>
<div class="main-content">
  <div class="parent">
    I'm the Parent
  </div>
  <div class="container">
    <div class="child">I'm the Child</div>
    <div class="other-stuff">I'm the Other Stuff</div>
  </div>
</div>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement