What is the best way to horizontally center a child div within its parent container while keeping it fixed at the top?

I am struggling to center a child div horizontally within its parent div while also fixing it to the top of the parent. I have tried various approaches in CSS, but so far I haven't been successful :-( I can either center it or fix it to the top, but when I try to do both, the child div remains fixed in its default position (to the left).

EDIT: The child div must remain fixed to the top so that when other children overflow, they can be scrolled while it stays in place.

Answer №1

Utilize flexbox - the significant difference between Bootstrap3 and Bootstrap4 is the transition from floats to flexbox!

Example:

#parent{height:100px;background:red;}
#parent{display:flex;align-items:flex-start;justify-content:center;}

#child{background:yellow;}

XXX#child{flex-grow:1;text-align:center;} /* Uncomment if you want row to be full-width */
<div id="parent">
  <div id="child">
     Here is some text
  </div>
</div>

References:

Fantastic flexbox cheat sheet

Even better concise Video Tutorial

Answer №2

.container{
  position: relative; // Crucial for layout
}

.box{
  position: absolute;
  top:0;
  left: 50%;
  transform: translateX(-50%);
}

Answer №3

Give this code a try

<div class="container">
  <div class="child"></div>
</div>

Check out the accompanying CSS

.container {
  width: 100%;
  background-color: orangered;
  height: 200px;
  position: relative;
}
.child{
  width: 200px;
  height: 100px;
  background-color: brown;
  position: fixed;
  left: 50%;
  right: 50%;
  transform: translateX(-50%);
}

Answer №4

Here is the potential answer:

.child{
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
}

A big thank you to @Prithwee Das for providing the helpful transform hint.

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

Guidelines on how to extract linked text using Selenium in C#

I am attempting to automate the download of files from a lined text, but unfortunately, I am having trouble getting it to work. I am a beginner with selenium. Here is the HTML code of the site: Ttnc-18p - 17.34 GB <table class=&q ...

Is it possible to nest a section tag within an anchor tag?

Is it possible to nest a section tag within an a tag? For example: <a href="mylink"> <section class=mysection> <h2>my headline</h2> <p>my paragraph</p> </section> </a> Thank you for your help ...

The Radix UI Theme's dark mode isn't taking effect

I'm having trouble getting the dark mode to work properly in my Radix UI app. Despite setting appearance="dark", nested components like Box and Card remain light. Interestingly, other props such as accent color seem to be working fine. It&a ...

What is the method for setting the current time as the default in a time picker?

Below is a snippet of code where I attempt to implement a date picker and set the current time as the default value. .HTML <input type="time" [(ngModel)]="time"> .TS time; constructor() { this.time= new Date(); } ...

Manipulate inherited CSS styles from an external source

Currently, I am working on creating a pagination using the NG-Bootstrap pagination component. However, I encountered an issue where I need to modify or specifically remove some CSS properties that are applied by default in the NG-Bootstrap library. Is ther ...

Utilizing Bootstrap to arrange table cells in a shifted manner

I'm new to utilizing bootstrap in web development. I've been exploring various examples of bootstrap templates that include tables, and I noticed that when I resize my browser window, the table adjusts accordingly. Now, I'm curious to know ...

Incorporate a personalized menu into the FullPage.js section

Seeking advice on fullpage.js for my website - Can a non-sticky menu be added to all sections without affecting loading speed? I attempted to include the menu code in each section, but it slowed down my website. Any suggestions or tips? ...

Preventing text wrapping in Boostrap 4 tabs - what's the solution?

Currently utilizing Boostrap 4 for a simple 4 tab horizontal navigation. The desired display on big screens is: "Some text [font-awesome-icon]" x 4 tabs. For smaller screens, it should show as: "[font-awesome-icon]". While the display works, the font-aweso ...

A versatile jQuery function for extracting values from a :input selector

Is there a universal method in jQuery to retrieve the value of any :input element? I pose this question because I have a webpage containing select and checkbox inputs, as seen in the code below: for (var i = 0; i < arguments.length; i++) { ...

How can HTML output be automatically indented?

Seeking a way to automatically indent the HTML generated by my PHP script. I currently use HTML Purifier for validating internal textbox inputs, but I have reservations about using HTML Tidy due to its lack of active development and numerous reported bugs ...

Guide to utilizing JavaScript for a basic gaming experience

Looking to incorporate multiple divs that will vanish upon being clicked, while also increasing the score by 1 through javascript. Any suggestions on how to accomplish this? ...

The navigation bar has surpassed the content limit and overflow-y is visible

My website has a navigation bar with content that exceeds the desired limit, and I want the rest of the content to be shown in overflow-y. However, an issue arises when hovering over the content, as the content is displayed (likely due to fixing min-heigh ...

Seeking assistance with implementing Styles using the .css() function in Jquery. Any guidance is appreciated

This particular style is exactly what I am looking for. body{ background: url("img/Background_Home.jpg") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

The div I'm trying to position at the bottom is currently wedged between other divs

My goal is to move the gray rectangle (<div class="brand"> </div>) below the other elements automatically. Currently, it's stuck between the header and two other body divs. Being a beginner, I'm unsure how to fix this. I've tried ...

What is the best way to resize an image to match the height of its flex item sibling?

After reading this answer, I attempted to adjust the size of a flex-item img element to match the height of its sibling. The height was adjusted correctly and the image shrunk accordingly while maintaining its aspect ratio, but the img element still took u ...

Modifying the color scheme of Bootstrap

In order to simplify referencing, I am establishing new theme colors as shown below, allowing me to use classes like bg-red instead of bg-danger or text-purple, and so forth. $primary : #24305e; $blue : #375abb; $indigo : #796eff; ...

What are some methods for applying border styles to the first and last row of a table using Material UI?

In my current project, I am utilizing the combination of Material UI and React Table. Recently, I was asked to implement an expandable row feature, which I successfully added. Once the user expands the row, we need to display additional table rows based on ...

Ar.js results in objects experiencing deformation or modification when manipulated

Recently, I started experimenting with Ar.js and encountered an issue where the objects displayed on the screen seemed distorted. To illustrate this problem, let me share a basic A-Frame example featuring a perfectly round sphere: <!DOCTYPE> <html ...

AngularJS: splitting the parent <div> into multiple sections every nth element

I have an array of strings in Javascript and I am attempting to use AngularJS to create nested <div> elements. var arr = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"]; My goal is to group every 3 elements together like so. <div class="pare ...

Combining onmousedown and onchange for optimal event handling

There is a div with three slide-bars, each representing an 'rgb' value with a range of 0-255. When the slide-bars are dragged, the background-color of the div should change accordingly. Currently, an 'onchange' event is called to a func ...