To align the second child element in the middle of a parent div using a floating child element

This is the HTML structure I am working with.

<div id="parent">
    <div class="child">
        <h1>title</h1>
        <p>content</p>
    </div>
    <div class="child">
        <h1>title</h1>
        <p>content</p>
    </div>
    <div class="child">
        <h1>title</h1>
        <p>content</p>
    </div>
</div>

Along with CSS styles for these elements:

#parent{
    padding: 0px 8px;
    overflow: auto;
    max-width: 100%;
    max-height: 100%;
}
.child{
    width: 300px;
    display: block;
}
.child:first-child{
    float: left;
}
.child:last-child{
    float: right;
}
.child:nth-child(2){
/* what is the style here to make it center? */
}

As seen in the code above, the goal is to align the child elements properly within the parent div. The first child should be floated left, the last child floated right, and the second child positioned exactly between them. I have tried using 'margin: 0 auto;' on the middle child element, but it did not work as desired. I am currently seeking a precise solution to achieve the desired layout of three aligned boxes inside the parent div.

Answer №1

Just let it drift:

#container{
    margin: 0px 8px;
    overflow: auto;
    max-height: 100%;
    float:left;
    width:900px;
}
.box{
    width: 300px;
    display: block;
    float:right;
}

Check out this demo

Answer №2

Align your second div to the left and add a left margin if necessary. For a responsive design, consider using percentages instead of fixed pixels. Hopefully that clarifies things.

.child:first-child, .child:nth-child(2) {
    float:left;
}

.child:nth-child(2) {
    /* How can we center this element? */
    margin-left: adjust either pixels or %;
}

.child:last-child {
    float:right;
}

JSFIDDLE (Responsive):

http://jsfiddle.net/83Gg2/

Answer №3

If you want to avoid floating elements next to each other, try using the display: inline-block property instead. It may seem like a hack, but it's actually a cleaner solution:

#parent{                                                                        
     width: 100%; 
     height: 100%;                                                  
     max-width: 100%;
     max-height: 100%;                                          
     overflow: hidden;                                                           
}                                                                                
.child{                                                                         
     width: 33%;  // Ensure equal distribution for 3 children.                                                               
     display: inline-block;                                                       
}     

The key is to remove any space between child elements in your HTML code, as the display:inline-block property only works when elements are adjacent without space. Your HTML should be structured like this:

<div id="parent">                                                               
     <div class="child">                                                         
         <h1>title</h1>                                                          
         <p>content</p>                                                          
     </div><!--                                                                  
     --><div class="child">                                                      
         <h1>title</h1>                                                          
         <p>content</p>                                                                               
     </div><!--                                                                  
     --><div class="child">                                                      
         <h1>title</h1>                                                          
         <p>content</p>                                                          
     </div>                                                                      
 </div>                                                                          
 ~     

For a live example, check out this JsFiddle link

~
~

Answer №4

Using flexbox makes this process extremely easy:

#container {
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}
.item {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

Remember to include prefixes and older syntax for compatibility with various browsers, you can check http://caniuse.com/#search=flexbox for more information.

I have created a simple example for you on CodePen: http://codepen.io/anon/pen/tribL

Answer №5

Alright, since you also mentioned jquery, here is a solution using jQuery.

If you prefer not to set a fixed width for #parent but want a fixed width for .child, you can use this method. It is compatible with different browsers including older ones.

Check out the DEMO http://example.com/demo

$(document).ready(function(){
    centerElements();
    $(window).resize(function() {
        centerElements();
    });
});
function centerElements(){
    var margin = ($('#parent').width() - $('.child').width() * 3) / 2;    
    $('.child').eq(1).css({
        'margin-left': margin + 'px',
        'margin-right': margin + 'px'
    });
}

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

Is it recommended to differentiate between users and usersList in node.js?

Exploring the world of Node.js and Express, I find myself in the process of constructing a server after completing most of the frontend work with React for a complex application. Within the app structure, I decided to segregate mock data into users and use ...

Trouble retrieving an array within a nested immutable object

Can you do this? render() { var items = this.props.items.course_list; console.log(items); return ( <div> </div> ) } Outcome: https://i.sstatic.net/ugSsN.png Attempt to access course ...

`What is the proper way to retrieve data from ajax.done() method?

Using Ajax, I am retrieving the nickname and attack_point data. var nickname; $.ajax({ method:'GET', url:get_gamestart_api_url, }).done(function(data){ $get_id.append("<li class='nickname&apo ...

Transmitting the data from the input field

I'm currently stuck trying to figure out the logic behind my Ajax form submission. I am attempting to POST my form using Ajax and send certain values in the correct manner. Here is an example of my form: <form method="post" action="~/AJAXcalls/ca ...

Discover the obscure element

Note that the number of parent elements may vary. It could be just one or multiple. I'm experimenting with different methods to locate the outermost parent <div> element that contains a <div> element with the class rat along with a label. ...

Is there a way to initiate an Edge animation when an onclick event occurs?

I am interested in incorporating an interactive Adobe Edge animation that activates upon the click of a conventional HTML form button. Could you please guide me on how to achieve this? ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Using Jquery to allow users to dynamically add <a href> links to localstorage

In the context of a work project, there is a bookmark page with internal links already set up. However, I am looking to allow users to add custom bookmarks with their own URLs dynamically and save them via local storage. This could potentially include an i ...

What is the best way to attach an event listener to detect the coordinates where a click occurs inside a div element?

Imagine a situation where you have a div container measuring 200px by 500px. The goal is to implement an event listener that can identify the x and y coordinates within this div when it is clicked. What would be the approach to achieve this in React? ...

Enhancing website security using Content Security Policy in conjunction with Google Closure

Implementing CSP for my web application is a top priority. Here's the policy I have in mind: "default-src 'self' gap: cdvfile;" I rely on google closure for my javascript needs. However, it seems that without javascript optimization, my ...

What is the process for having HTML open a hyperlink in a new window?

I am facing the following issue: <p class="bigfont"> <img width="4%" src="images/Youtube.png" class="float-left"/ > <a href="\\OC2-RMGFS\Public\Safety\runhidefight-eng.wmv" target="_blank" title="Response to ...

Concealing a hyperlink within a DIV by removing or hiding it

I am looking to temporarily hide or remove a specific link (team.aspx) within a drop-down menu, with the intention of adding it back in later. Here is my current code: <div id="nav_menu"> <ul id="nav"> <li class="current"><a href= ...

How can we optimize axios requests with lodash debounce?

Utilizing a state prop named network busy status to control elements in the UI. Due to the rapid changes in status, my spinner appears overly active. Is there a simple method, utilizing lodash _.debounce, to throttle this section of code? const instance ...

Using Ajax, jQuery, and PHP in Internet Explorer 9 is possible, but it may not work in Internet

I am encountering an issue with my jQuery/AJAX script that posts to a php file in order to retrieve XML data. The problem arises when I print the data and notice that all the HTML source code is being returned instead of properly parsed XML, especially in ...

JavaScript function to evaluate true conditions

I am encountering an issue while calling sub functions connected to if statements within my main function. Even though the sub functions are supposed to return true or false, the expected alerts are not appearing. if (functionAAA()){ alert("111 ...

Utilize ngModel in conjunction with the contenteditable attribute

I am trying to bind a model with a tag that has contenteditable=true However, it seems like ngModel only functions with input, textarea or select elements: https://docs.angularjs.org/api/ng/directive/ngModel This is why the following code does not work ...

Are you interested in monitoring the website's past activity?

Similar Question: How to maintain browser history when utilizing Ajax? I've been trying to find a solution for this issue, but so far I haven't had any luck. Here's the thing: I created a template for my homepage that might not be perfe ...

Determine the length of a string in JavaScript and PHP taking into account "invisible characters" such as and

I have a textarea where users can input text, and I want to show them how many characters they have left as they type using JavaScript or jQuery: var area = 'textarea#zoomcomment'; var c = $(area).val().length; After that, the text is validated ...

Ways to avoid losing data when a page is refreshed

After encountering a frustrating issue with my form, I turned to research in hopes of finding a solution. However, each attempt has resulted in disappointment as the data is lost every time the page is refreshed. If anyone has advice on how to prevent th ...

The data in a NodeJS-generated JSON file is incorrect

In an attempt to generate a well-formatted JSON file containing the names of files (testfile1, testfile2, testfile3) located in a directory named "uploads," I wrote the code below: const fs = require("fs"); let toJson = {files: []}; let file = new Object() ...