Ensure two CSS components occupy the entirety of their container, positioned next to each other, with margin spaces between

I am looking to make two elements take up a precise percentage of the parent's width, while also including margins between them. Here is my current setup:

<div class='wrap'>
  <div class='element'>HELLO</div><div class='element'>WORLD</div>
</div>​
.wrap {
  background:red;
  white-space:nowrap;
  width:300px;
}
.element {
  background:#009; color:#cef; text-align:center;
  display:inline-block;
  width:50%;
  margin:4px;
}

When viewing it on http://jsfiddle.net/NTE2Q/, you can see that the children exceed the wrapper:

Is there a way to ensure they stay within the boundaries? Unfortunately, there doesn't seem to be a box-sizing:margin-box solution for this scenario.

Answer №1

Innovative Method #1 - Modern CSS3 calc()

By utilizing CSS3's calc() length, you can achieve this by specifying the width of the .element as follows:

.element {
  width: 49%;                     /* not ideal for older browsers */
  width: calc(50% - 8px);         /* recommended solution for IE9+, FF16+ */
  width: -moz-calc(50% - 8px);    /* compatibility for FF4 - FF15 */
  width: -webkit-calc(50% - 8px); /* browser support for Chrome19+ and Safari6+ */
}

Demo: http://jsfiddle.net/NTE2Q/1/

Visit http://caniuse.com/calc for information on which browsers and versions offer support for this feature.

 


Innovative Method #2 - Traditional Wrapping

An alternate approach is to stack multiple elements together, wrapping each 'element' within a container that has a width of 50% and a padding of 4px:

<div class='wrap'>
  <div class='ele1'>
    <div class='element'>HELLO</div>
  </div><div class="ele1">
    <div class='element'>WORLD</div>
  </div>
</div>​
.ele1 {
    display:inline-block;
    width:50%;
    padding:4px;
    box-sizing:border-box;          /* Ensure that 50% includes the padding */
    -moz-box-sizing:border-box;     /* For Firefox                             */
    -webkit-box-sizing:border-box;  /* For legacy mobile Safari                   */
}
.element {
    background:#009; color:#cef; text-align:center;
    display:block;
}

Demo: http://jsfiddle.net/NTE2Q/2/

 


Innovative Method #3 - Leveraging (CSS) Tables

A similar outcome can be achieved by treating the wrapper as a 'table' and each element as a cell in the same row. In this way, spacing between elements becomes insignificant:

<div class='wrap'>
  <div class='element'>HELLO</div>
  <div class='element'>WORLD</div>
</div>​
.wrap {
    background:red;
    width:300px;
    display:table;
    border-spacing:4px
}
.element {
    background:#009; color:#cef; text-align:center;
    width:50%;
    display:table-cell;
}
​

Demo: http://jsfiddle.net/NTE2Q/4/

It should be noted that this final method eliminates the 4px gap between the two elements, whereas the initial two methods result in an 8px space between items and a 4px margin at the edges.

Answer №2

Have you considered utilizing the CSS border property in combination with background-clip to achieve the effect you're looking for? Remember to include appropriate vendor prefixes to ensure cross-browser compatibility.

Check out this JSFiddle demo

.wrapper {
    background-color: red;
    white-space: nowrap;
    width: 300px;
}

.element {
    background: #009;
    color: #cef;
    text-align: center;
    display: inline-block;
    width: 50%;
    border: 4px solid rgba(0, 0, 0, 0);
    box-sizing: border-box;
    background-clip: padding-box;
}

Answer №3

I struggled to find a consistent technique that worked across different browsers. Ultimately, I discovered a unique approach using the display:table-cell property to position multiple elements side by side. Check out this example for a demo.

Here's the CSS:

    display:table-cell;
    background:#009; color:#cef; text-align:center;
    width:22%; /*Adjust percentage based on number of elements*/
    border:4px solid rgb(255,0,0);/*Use border color instead of background color*/

You no longer need a wrapper element since the div now acts like a <td>.

Answer №4

While I highly recommend utilizing Phorgz's calc() method whenever available, I also wanted to introduce a traditional approach that involves using just one container and the CSS property position: relative to achieve the desired outcome.

.two-blocks-by-side() LESS Mixin:

.two-blocks-by-side(@padding) {
  padding: @padding (@padding + @padding / 2);
  font-size: 0;

  & > div {
    position: relative;
    display: inline-block;
    font-size: initial;
    width: 50%;

    &:first-child { left: -1 * @padding / 2 };
    &:last-child { right: -1 * @padding / 2 };
  }
}

Check out this JS Bin demo for an example

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

What could be the reason for the top alignment of only a portion of the cell

Here is the code snippet I am working with: <html> <head> <style> table.t_group { border: 2px solid black; margin: 0 auto 0 auto; } table.t_group > tbo ...

Guide to customizing the CSS styles of various components within a Material UI Dialog

Let's take a look at this snippet for creating a Material Dialog in code: <Dialog open={this.props.open} onClose={this.props.closeAtParent} PaperProps={{ style: { minHeight: '75vh', minWidth: '75vw', ...

Is there a way to align six columns on the left side and have a dynamic column on the right that fills the width of the browser window?

Is there a way to make a fluid container in Bootstrap 5 that contains a normal container on the left with 6 columns of content, while allowing the right side of the container to expand to the end of the browser window? When using a normal fluid container, ...

How can Angular CLI prevent the submission of an HTML form unless a previous option has been selected

I am currently working on a form that contains select fields with various options pre-populated. <form [formGroup]="selectVehicleForm"> <select formControlName="Manufacturer"> <option *ngFor='let ...

How can I use JQuery to select an element with a style attribute in Internet Explorer?

When using JQuery, I have set my target to be the following: <li style="margin-left: 15px;">blah<li> I am using this code to achieve that: $(".block-category-navigation li[style='margin-left: 15px;']").addClass('sub-menu' ...

What is the best way to create a hover effect exclusively for the hamburger icon, and not for the close button

I am facing an issue with the code snippet below: .btn-menu:hover .btn-menu__bars::before{ transform: translateY(-0.5875rem); } .btn-menu:hover .btn-menu__bars::after{ transform: translateY(0.5875rem); } Is there a way to make this hover effect only a ...

Mapping an array in ReactJS based on the specific order of another array

In my experience with Unmitigated, the answer proved beneficial. If you're arriving from a Google search, please scroll down for more information. Order: [ "567", "645", "852", "645", "852", "852 ...

Rotate a shape to form a Rhombus at the center

I used the transform CSS property to create a rhombus, but I noticed that the center point of the shape is off-center to the right rather than in the middle. Can anyone help me figure out how to fix this issue? You can view my code here. .rhombus{ width ...

django is not able to load staticfiles from the statifiles_dirs directory

I have placed my style.css in the directory appname/static/appname/. In my settings.py, this is what I have: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static/"), ) When I try to load it in my base.html like t ...

Struggling with CSS issues in ASP.NET 4.6

For the past few months, I've been diligently working on a project that suddenly hit a snag today. Upon inspecting my website, I noticed that all my button sizes appear to be uniform. I typically use Chrome's developer tools to troubleshoot my we ...

Arranging the 1st element of the 1st row to be placed at the end using CSS Flex

One of my challenges involves choosing between two options: https://i.sstatic.net/JpWiGfW2.png In my project, I am utilizing a container with flex-wrap: wrap to showcase items of equal dimensions. However, the first item in this container stands out due t ...

Is it feasible to verify for vacant dates with a single click?

Is there a way to determine if a date value is empty, and if it is, display a popup indicating so? After some research, I stumbled upon a similar issue where the date value was always filled with a default "mm/dd/yyyy" value. The solution provided involv ...

Tips for ensuring the Google+ JavaScript tag is W3C compliant

I have a Google+ button on my website that is functioning properly. However, when I run it through the W3C validator, an error is detected: The text content of the script element does not meet the required format: It was expecting a space, tab, newlin ...

Personalized form outlines

I'm designing a Valentine's Day theme for my website and I was wondering if it's possible to create custom form borders, like a heart shape, without having to hard-code everything. I could always insert an image where needed, but that seems ...

Design a modern slider with a button that triggers a pop-up modal window

Recently Updated I am working on a testimonial slider using slick slider, and I want to incorporate a modal within each slide. In my custom post type 'Testimonials' (also known as 'getuigenissen' in English), I have various Advanced C ...

Buttons within the Bootstrap carousel caption cannot be clicked

I am currently designing a webpage with a Bootstrap carousel that includes a paragraph caption and two buttons. However, the buttons are not functioning as clickable links - when clicked, nothing happens. {% block body %} <div id ="car-container"> ...

The default action is not triggered when the click event occurs

Hey there, I have been working on this <ol> list of events using jQuery (version 1.4.2). Everything is set up within the $(document).ready() function. Something strange is happening where when I click on the <li>, it triggers a click on the co ...

What causes line-height to be overlooked in a span element but effective in a div element?

Take a look at this example: CSS: How to reduce line spacing of text? I've experimented with it, and I noticed that the CSS property line height is not very effective when applied to a span element. Why is this the case? Why does it only work properl ...

Error message appearing repeatedly and submit button functioning only after second click

I am currently working on my CS50 Final Project, where I am in the process of designing a web app using Flask. Specifically, this issue arises in the login/register page where I am attempting to verify if the username is already taken (through jsonify) and ...

I'm feeling a bit lost on where to go next with this JavaScript

I've been working on a project in Python where I need to retrieve a file, store it in an array, and display a random string from the array on HTML. However, I have no experience with JavaScript and am unsure how to proceed. I suspect there may be an i ...