``Despite setting display block, margin auto is not being adhered to as expected

Trying to position two label elements on either side of a div container has been tricky. Despite using various display properties like display: block and display: inline-block, the margins are not behaving as expected.

  div {
    color: #ffffff;
    background-color: #3f3f3f;
  }
  label:nth-of-type(1) {
    margin-left: 5px;
  }
  label:nth-of-type(2) {
    display: block;
    <!-- display: inline-block; -->
    margin-right: 5px;
    margin-left: auto;
  }
<div>
  <label>Left side label</label>
  <label>right side label</label>
</div>

The issue becomes evident when the code is executed, with the second label failing to adhere to the specified margins and appearing below the first one.

Answer №1

For margins to work with auto, the label needs a width and display:block.

Using flexbox is now more versatile for achieving this layout.

div {
    color: #ffffff;
    background-color: #3f3f3f;
    display:flex;
    flex-flow: row nowrap;
    justify-content: space-between;
}

label:nth-of-type(1) {
    margin-left: 5px;
}

label:nth-of-type(2) {
    margin-right: 5px;
}
<html>
  <body>
    <div>
      <label>Left side label</label>
      <label>right side label</label>
    </div>
  </body>
</html>

Answer №2

Utilizing more current techniques like CSS Grid or Flexbox can achieve the desired outcome. However, I will present a solution using pure CSS to align with the level of complexity in OP's code.

Applying display: inline-block to both labels is essential to treat them as block elements and keep them on the same line. Additionally, setting a width provides a container for adjusting text placement. In this scenario, we'll go with width: 50%.

Important: When inline-block elements occupy an entire width: 100%, the labels may appear on separate lines unless you eliminate whitespace between the elements in the HTML. For further insights into this behavior, check out this article here, along with a related CodeSandbox example.

I've adjusted the width calculation by replacing margin-left and margin-right with padding to ensure consistent spacing on both sides.

HTML:

<body>
    <div>
      <!-- Remove whitespace between labels to prevent exceeding width: 100% -->
      <label>Left side label</label><label>right side label</label>
    </div>
  </body>

CSS:

div {
  color: #ffffff;
  background-color: #3f3f3f;
  padding: 0 5px;
}

label {
  display: inline-block;
  width: 50%;
}

label:nth-of-type(1) {
  text-align: left; /* Optional but allows explicit control over alignment */
}

label:nth-of-type(2) {
  text-align: right;
}

Codepen

Answer №3

Forget about setting the display property, just keep it inline and experiment with the float property for positioning.

<style>
div {
  color: #ffffff;
  background-color: #3f3f3f;
  display: block;
  height: 20px;
  width: 100%;
  
}

label:nth-of-type(1) {
  margin-left: 5px;
  float: left;
}

label:nth-of-type(2) {
  float: right;
  margin-right: 5px;
}
</style>
<html>

<body>
  <div>
    <label>Left side label</label>
    <label>right side label</label>
  </div>
</body>

</html>

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

Using jQuery to modify CSS properties in the propertyName

With jQuery v1.6.4, I am attempting to dynamically format some objects. Take a look at my code snippet: <html> <head> <script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script> <script type="text ...

The Media Queries in the Wordpress html5blank theme are failing to function properly

While using the html5blank theme to develop a WordPress site, I noticed that my media queries are functioning properly locally. However, when I add them to the WordPress style.css file, they seem to stop working. Even after stripping away all other media q ...

What is the best way to incorporate a set of buttons and dynamically update them by using next and previous buttons?

Currently, I have code for two sets of buttons. How can we add functionality for next and previous buttons? <div id="chart-section-wrapper" class="container"> <div id="chart-section"> <div class=& ...

Tips for adjusting the side layout in Bootstrap

Is there a way to keep the side navigation fixed when scrolling down? See it in action here <div class="page-container"> <!-- top navbar --> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="conta ...

Use jQuery to permit only numeric characters and the symbol "-" to be entered into a textbox

I have been working on a JQuery script that only allows users to input numbers in a text field. However, I am now trying to modify the code to also allow users to enter "-" (hyphen), but so far it's not working as expected. If anyone can provide assis ...

Adjusting the height of the Owl Carousel div to enhance image hover effects

Seeking help with implementing a hover effect on an img within an Owl Carousel div. I have applied a simple CSS transition to the Owl Carousel container div, but the Carousel is automatically setting a standard height. Images included for reference. I have ...

The D3.js text element is failing to show the output of a function

I'm having an issue with my chart where the function is being displayed instead of the actual value. How can I make sure the return value of the function is displayed instead? The temperature values are showing up correctly. Additionally, the \n ...

What is the best way to create text boxes that can expand and collapse within a UIWebView?

I am looking to present text in a UIWebView with expandable or collapsible boxes that contain titles. The user should be able to tap the bar of a collapsed box to expand it. Is there a simple solution available that can be easily integrated into a local ...

Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class=" ...

Generate a dynamic text-box and drop-down list using HTML and JavaScript

My current project involves generating dynamic text-boxes based on the selection from a drop-down list and input field. https://i.sstatic.net/CMtW9.png When a user chooses 'Option 1' from the drop-down list and enters input such as 'grass& ...

Deactivate button using Javascript

Can anyone assist me with this issue I am having? I currently have a button set up as follows: <input type="button" id="myButton" name="myButton" value="ClickMe!!" onClick="callMe()"/> I need to disable the button using jQuery, standard javascript ...

Storing the values of three checkboxes in individual variables to be passed into distinct columns

Below is the HTML code for checkboxes, with a function that limits only three selections: <form class="interestSearchCriteria"> <input type="checkbox" name="walking" value="Walking"> Walking <input type="checkbox" name="running" value=" ...

The bootstrap table did not meet my expectations as I had hoped

I am currently using Bootstrap to create a basic two-column table similar to the one on the Bootstrap website here: http://getbootstrap.com/css/#tables. To achieve this, I have implemented a javascript function to display the table as shown below: $(&bso ...

Incorporating additional options onto the menu

I recently designed a menu on https://codepen.io/ettrics/pen/ZYqKGb with 5 unique menu titles. However, I now have the need to add a sixth title to the menu. After attempting to do so by adding "strip6" in my CSS, the menu ended up malfunctioning and looki ...

Is it possible to add a jQuery-generated element to pure vanilla JavaScript?

I am facing a challenge in creating a new notification div when an event is triggered. Ideally, I would normally achieve this using jQuery by utilizing something like $("myDiv").append(newDiv). However, in this case, the item selector to which the new div ...

Learn how to display a "not found" message in a React.js application

I have a piece of code where I am sending a post request to an API and retrieving all the data from the API in a table. I am trying to find currency data based on the currency name, if found I display the data in a div, if not found I want to print "not ...

The Glyphicon icon fails to appear on the initial page load and only shows up after refreshing the

I have been utilizing bootstrap.min.css from bootstrap v3.3.5 which I downloaded from http://getbootstrap.com and used it locally. However, I encountered an issue with glyphicons when running it on IE 9 and above. The glyphicon icon disappears on the first ...

Looking for guidance on integrating Forms with VueX and script setup? Are you utilizing v-model in your implementation?

UPDATE: I'm contemplating whether or not to abandon VueX entirely due to its outdated status, with Pinia being the preferred choice nowadays. Can someone confirm this? https://stackblitz.com/edit/vue-script-setup-with-vuex-hmrk5d?file=src/store.ts ...

Error in line 36: firebase.auth function is undefined

Snippet of index.html code <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" ...

Sending an ID from an array within a *ngFor loop to a different component in Angular: a step-by-step guide

I have a collection of items that I loop through using ngFor. My goal is to pass all its attributes to another component. I attempted to accomplish this with the following code: *ngFor='let item of postList [routerLink]="['/detailed-post&ap ...