Position a div in the center and add a right menu to it

Looking to centralize a main div and add a fixed menu to the right side of it. The goal is for the main div to remain centered while the right menu "sticks" to the center div.

At the moment, I've used flex to center the div, but it has resulted in both items being centered (meaning the main div isn't truly at the center).

This is the layout I want:

https://i.sstatic.net/7Bqy5.png

Current layout:

https://i.sstatic.net/PrZze.png

The code I currently have (using React with styled components) looks like this:

Container:

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 how it renders:

<DivContainer>
  <MainDiv />
  <MenuDiv />
</DivContainer>

Answer №1

One option is to nest the sidebar within the container and use a negative margin to push it out

body,
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">
    content
    <div class="sidebar">
      sidebar
    </div>
  </div>
</div>

ps: for the snippet click full page

Answer №2

If you want to achieve centering without affecting the layout, one way to do it is by using a zero-width div with overflow visible:

#container {
    display: flex;
    justify-content: center;
}

#content {
    width: 50%;
}

#spacer {
    width: 0;
    overflow: visible;
}

#sidebar {
    width: 100px;
}
<body>
  <div id="container">
    <div id="content">
        Centered content
    </div>
    <div id="spacer">
        <div id="sidebar">
            Sidebar content
        </div>
    </div>
  </div>
</body>

Answer №3

Enclose it in a separate div with the same width as the main div and establish a minimum width for its child.

.wrapper {
      display: flex;
      width: 300px;
    }
    .container {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
    }
    .main {
      width: 300px;
      min-width: 300px;
      min-height: 200px;
      background-color: aquamarine;
    }

    .menu {
      width: 80px;
      min-width: 80px;
      min-height: 200px;
      background-color: cadetblue;
      position: relative;
    }
<div class="container">

  <div class="wrapper">
    <div class="main"></div>
    <div class="menu"></div>
  </div>

</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble connecting: MongoDB Node.js client hangs during connection attempt

The node-mongodb-native for node.js seems to be causing a hang when using MongoClient.connect(...), while the mongodb-client (shell command line) works fine in the terminal. Any ideas on what might be causing this issue? var MongoClient = require('mo ...

Arranging blocks within blocks? Placing additional text underneath a block

Looking to append some text at the end of a block called .label. Inside this block, there is a sub-element called .label_title, and below that is a picture/link enclosed in another block. Under the picture/link, I wish to include a short description while ...

The AJAX functionality is not triggering the necessary C# controller method

I have been facing a challenge with my AJAX implementation as I am still new to using it. The problem arises when trying to reach the C# method it should call - even after setting a breakpoint, the code is never reached and no errors are displayed. While ...

Scripting method to transfer multiple subdirectories using a cpanel.yml file (excluding the use of the wildcard)

I have been referring to the documentation found at My current issue is that when I try to copy my subfolders, it doesn't work properly unless I use a workaround. The only way I am able to achieve the desired outcome is by utilizing the following co ...

How do I limit search bar queries to only display results from my website and provide suggestions?

Is there a way to customize the search bar on my website so that it only finds results within my pages and also provides suggestions? ...

JavaScript's regular expression does not fully match until the end of the given string

In my JavaScript code, I am validating dates using a regular expression. The specific regular expression I am utilizing is as follows: /^(((((0?[1-9])|(1\d)|(2[0-8]))\/((0?[1-9])|(1[0-2])))|((31\/((0?[13578])|(1[02])))|((29|30)\/((0?[1 ...

Integration issues in RetinaJs and jChartFX collaboration

I am currently utilizing jChartFX for charting purposes on my website. I have included the following line of code to bring in the footer: <?php include $_SERVER["DOCUMENT_ROOT"].'/footer.php' ?> The footer contains a script reference like ...

Storing data retrieved from a GraphQL response into the sessionStorage: A step-by-step guide

I am facing a challenge in saving my GraphQL response in sessionStorage to access it across different parts of the application without making repeated API calls. I am currently using the useQuery hook with a skip property to check if the data is already st ...

Manipulating arrays in JavaScript through HTML processing

I'm encountering an issue while trying to send an array to a JavaScript function. Here's what I have so far: Within the controller: @data = [{date: '2014-08-17'}, {date: '2014-08-20'}].to_json In the view: <%= content_t ...

Issue with alignment of Bootstrap inline form field on top and bottom levels

I seem to be encountering an issue highlighted in the image below: My goal is to have the state dropdown perfectly aligned with the top and bottom edges of the other two controls. Here's the code snippet I've used to create this section of the i ...

There seems to be an issue with d3js bar charts as they are not displaying on the screen and there

Recently, I started delving into the world of D3js and decided to try my hand at creating some bar charts. However, despite my efforts, the bar charts failed to display on the screen. <!DOCTYPE HTML> <html> <head> <title> My D3 Pra ...

What is the most effective way to halt all AJAX processes on a webpage with jQuery?

Is there a way to use jQuery to halt all ongoing ajax processes on the page? ...

Invoking an HTML popup within a JavaScript function

Here is a question. In my project, I have the following JavaScript function: <script type="text/javascript" language="javascript"> $(document).ready(function(){ PopUpHide(); }); function PopUpShow(popup_title, pk_post_add){ document.getEl ...

React server initialization in progress

After completing the development of my react app, I encountered an issue when running npm start. The error message displayed was "'GENERATE_SOURCEMAP' is not recognized as an internal or external command, operable program, or batch file." My oper ...

Utilizing AJAX in jQuery Mobile for Collapsible Content

I am currently generating a variable number of these elements using a foreach() loop: <div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a"> <h1 style="white-space: normal"><?php echo $data['te ...

There is an irritating 5px gap between the divs in the Avada WordPress theme. While using margin-top: -5px helps to reduce this spacing, padding-top: -5

Struggling to remove a persistent 5px whitespace on my website eternalminerals.com See the issue highlighted in this screenshot: Trying to eliminate the whitespace by adjusting margins in Google Chrome, but unable to apply styles to Avada shortcodes: &l ...

BeautifulSoup: Leveraging find_all() to locate particular strings within HTML documents

Check out my current code snippet: from bs4 import BeautifulSoup import requests header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'} url = requests.get("https://d1baseba ...

Dynamic burger menu navigation

I am in the process of designing a full-page navigation overlay for my website to ensure consistency across all devices. Currently, I have two buttons - one to display the overlay and another to hide it. I am considering whether it would be more effective ...

Tips for utilizing temporary variables in JavaScript

Is there a way to set a variable based on the result of a function call without calling the function multiple times or adding unnecessary temporary variables? Even though it might be seen as premature optimization, I prefer to avoid that. One approach is ...

Ways to retrieve JSON data using getRequest

Hey there, I have a string that looks like this: {"Fruit":"Meat", "Vegetable":[ {"Name":"Author1","Date":"12"}, {"Name":"Author2","Date":"2"}, {"Name":"Author3","Date":"14"} . . . {"Name": "AuthorN", ...