What is the Best Way to Align a Float Element Perfectly in the Middle of Two Other Floated Elements?

I've encountered a challenge in centering text between two other texts.

My Code:

<div class="main-container">
    <div class="footer">
        <span class="left_edge">@left</span>
        <span class="center">@center</span>
        <span class="right_edge">@right</span>
    </div>
</div>

The Issue:

.footer{
    background: #e33;
    padding: 5px;
}
.left_edge{
    float: left;
}
.center{
    float: left;
}
.left_edge{
    float: right;
}

Seeking guidance on how to align the .center perfectly as illustrated in the correct example?

Answer №1

To achieve horizontal centering, one method is to adjust the display property of the middle element to inline-block, and then apply text-align: center to the parent element:

See Example Here

.footer {
    background: #3498db;
    padding: 10px;
    text-align: center;
}
.left_edge {
    float: left;
}
.center {
    display: inline-block;
}
.right_edge {
    float: right;
}

Alternatively, you can opt not to float the elements and utilize the following technique instead:

See Example Here

.footer > span {
    display: inline-block;
    width: 33.333%
}
.left_edge {
    text-align: left;
}
.center {
    text-align: center;
}
.right_edge {
    text-align: right;
}

Answer №2

Your solution may work perfectly in scenarios where the floating elements are consistently present and have fixed widths. However, if one or both of the elements are missing or if their widths vary, the central element may start shifting positions unpredictably.

Consider a situation where you need to display a multi-line list of values in a table format. If each value is placed in a separate column, the available space may not be utilized efficiently. On the other hand, aligning the elements within a single cell using floating elements may cause the central element to move off-center, as its position is calculated based on the total width, including the floating elements.

HTML:

<table>
<tr><td>1</td><td class="container"><span class="left">left</span><span class="center">center</span><span class="right"></span></td></tr>
<tr><td>2</td><td class="container"><span class="left"></span><span class="center">center</span><span class="right"></span></td></tr>
<tr><td>3</td><td class="container"><span class="left">left</span><span class="center">center</span><span class="right">right</span></td></tr>
<tr><td>4</td><td class="container"><span class="left"></span><span class="center">center</span><span class="right">right</span></td></tr>
</table>

CSS:

.container { width: 400px }
span.left { float: left }
span.center { }
span.right { float: right }

To address this issue, you can try the following approach:

span.center { position: absolute; left: 200px; width: 50% }

However, using absolute positioning may not always be feasible, especially if the table is within a scrollable container. Additionally, if pseudo classes like before and after are used for the floating elements, this solution may also not be viable.

So, what alternative options can we explore in such situations?

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 VS Code highlighting compatible with template string CSS in Emotion?

Is there a way to enable syntax highlighting for emotion's template string css in VS Code? I've been looking for plugins, but all of them seem to focus on snippets. I have tried using css({ camelCaseCssProps:...}), which works. However, I am att ...

Presenting CSV data in a tabular format using Angular and TypeScript

I am facing an issue with uploading a CSV file. Even though the table adjusts to the size of the dataset, it appears as if the CSV file is empty. Could this be due to an error in my code or something specific about the CSV file itself? I'm still learn ...

What prevents me from displaying the image in the Bootstrap tooltip?

I am currently utilizing the Bootstrap framework v3.3.0 for my website. I'm trying to implement an image as a tool-tip when the user hovers their mouse pointer over an icon. Here is the HTML code I have: <div class="col-sm-5"> <div class= ...

Is it possible to detect when a user reaches the end of a div without using a scroll event?

Seeking a JavaScript solution that can identify when a user reaches the bottom of a div with overflow: auto. While there are numerous solutions on Stack Overflow utilizing the onscroll event, I am curious if this can be accomplished using newer technology ...

Adjusting table dimensions according to webpage dimensions

When looking at the image below, you will notice a div that contains a table with some content. However, when resizing the web browser's page, the table goes beyond the boundaries of the div. https://i.sstatic.net/SRlzM.png My goal is to reduce the ...

Error in the code that I am unable to locate in JavaScript, HTML, and CSS

I need help creating a navbar that displays the active site using HTML and JS code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content=& ...

Generate random unique values from an array to populate a text input field in HTML. Display a message once all unique values have been shown

I have included an option code and text box below: <select id="sel" class="form-control input-lg" data-live-search="true"> <option value="">-- Choose Your Country--</option> </select><br/><br/><br/> &l ...

I am having difficulty centering the contents on the page horizontally

Struggling to achieve horizontal alignment, I suspect the floats are causing issues. Removing them disrupts the layout with left_wrap and right_wrap not staying next to each other. Check out this example on JSFiddle .main_wrap {width:100%;} .main_wrap_2 ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

Instructions for concealing and revealing a label and its corresponding field before and after making a choice from a dropdown menu

Currently, I am working on developing a form that will enable customers to input their order information. This form includes a selection list for payment methods, with three available options. If the user chooses either credit or debit card as the paymen ...

Insert text within the switch component using Material-UI

Looking to customize Material UI's Switch component with text inside? Check out the image below for an idea of what I'm going for. https://i.stack.imgur.com/KadRZ.png Take a look at my code snippet: import React from 'react'; import S ...

The text/font-weight of the header button is mysteriously shifting without warning

While creating a header for my webpage, I encountered an issue where the text family was changing when the dropdown menu was launched in Safari 8. Curiously, this behavior did not occur when using Chrome to launch the jQuery function. Even after attempting ...

Navigating into the forbidden territory of the if block that holds secrets untold

Encountering an issue with the angularjs $location feature. I have set up an auth interpreter that redirects to the login page if a 401 error (unauthorised) is returned by the server. In my app.js file, both the auth interpreter and the account data loadin ...

Width of the `div` element is expanding

I'm encountering an issue where a div container is automatically stretching to the full width of the page, instead of adjusting to fit the content within it. Below is the HTML code snippet: <!doctype html> <html> <!-- Head --> <h ...

Entering text into a field / Inserting data into a MySQL database / Presenting

I am facing a challenge that I'm uncertain how to resolve. The issue lies with a textarea on my form that permits the user to input data in the following format: Windows XP Home and Professional<br />(32 and 64 bit) Windows 7 Home and Professi ...

Markdown boasts of a sturdy partially-horizontal line

Is there a way to create a partially colored line in Markdown? I attempted using the following code: <hr style="border:0.3px solid green; width:40%"> </hr> However, instead of a partial green line, I am seeing a full gray line. Any idea on w ...

Implementing a PHP function to retrieve rating values when clicking on star icons

I am looking to implement a star rating system for users and update the database values accordingly after each rating. Below is my PHP code snippet: <?php foreach($genres as $genre){ $jsqla = mysql_query("select id,name,rate_score,rate_number,vide ...

Establish initial content for the specified div area

I need help setting page1.html to display by default when the page loads. Can you provide some guidance? Appreciate your assistance in advance. <head>     <title>Test</title>     <meta http-equiv="content-type" content="tex ...

Is there a way to include a minimize button on a MaterialUi Table enclosed in a Paper component for easy table reduction?

I am trying to add a minimize button to either minimize my MaterialUi Table or the Paper component that wraps it. Here is the code I have so far: <TableContainer component={Paper} style={{maxHeight:'inherit', maxWidth:'inherit', boxS ...

Can React JSX and non-JSX components be combined in a single project?

I'm currently faced with a question: If I have a parent component in JSX but need to include an HTML tag like <i class="fa fa-window-maximize" aria-hidden="true"></i>, which is not supported by React JSX (correct me if I'm wrong), can ...