Center a div and append a right menu to that div Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Center a div and append a right menu to that div without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I need to center a main div and append a fixed menu to the right of that item. I need the main div to stay in the center and the right menu to “fix” to the centered div.

Currently, I’m using flex to center the div, but this is resulting in both items centering (meaning the main div is not truly in the center).

This is the desired layout:

desired result

Current layout:

current layout

The code appears as below (I’m using React with styled components):


const DivContainer = styled.div`
  display: flex;
  justify-content: center;
  position: relative;
  z-index: 60;
  width: 100%;

Main Div:

const MainDiv = styled.div`
  width: 300px;
  padding: 35px 15px;

Menu div:

const MenuDiv = styled.div`
  display: flex;
  cursor: pointer;
  flex-shrink: 0;
  flex-direction: column;
  margin-top: 85px;
  order: 10;

This is rendered as the below:

  <MainDiv />
  <MenuDiv />


You could put the sidebar inside the container and push it out with a negative margin right

html {
  height: 100%;
  margin: 0;

.container {
  height: 100%;
  width: 100%;
  border: 2px solid yellow;
  border-radius: 5px;
  box-sizing: border-box;
  margin: 5px;
  display: grid;
  place-items: center;

.center {
  width: 200px;
  height: 200px;
  border: 2px solid yellow;
  border-radius: 5px;

.sidebar {
  width: 50px;
  height: 200px;
  outline: 2px solid magenta;
  border-radius: 5px;
  /* important */
  float: right;
  margin-right: -50px;
<div class="container">
  <div class="center">
    <div class="sidebar">

ps: for the snippet click full page

We are here to answer your question about Center a div and append a right menu to that div - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji