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

Position the final list item in the column on the left side

Currently, I am facing an issue with creating spacing between li elements in a column layout. The problem arises when the last li in the column does not align to the far left edge of the column width. Take a look at the screenshot below for reference: Bel ...

Guide on darkening the surrounding div of an alert to give it a modal-like effect

I want to display an alert to the user in a visually appealing way. To achieve this, I am utilizing Bootstrap's alert class. Here is how I am showing the user a div: <div class="alert alert-warning alert-dismissible" role="alert"> Some text ...

The customized styling for Material Angular does not seem to properly apply to <md-card> elements within ui-views

I am trying to achieve a specific effect on the ui-views <md-card id="sidebar" flex="20" class="sche-card" layout-padding="true"> <div ui-view="card" autoscroll="false"></div> </md-card> However, I am facing an issue where the car ...

Is there a way to program custom key assignments for my calculator using JavaScript?

As a beginner in the world of coding and JavaScript, I decided to challenge myself by creating a calculator. It's been going smoothly up until this point: My inquiry is centered around incorporating keys into my calculator functionality. Currently, th ...

What is the purpose of activating hover styles when tapping on mobile devices?

On my button, you can see the color change when hovering: button { background-color: orange; } button:hover { background-color: darkorange; } Check out this example: https://jsfiddle.net/oepb5ks4/ While this works well on desktop, it's a diffe ...

Tips for creating a responsive background image without excessive scaling:

I'm currently working on a website with a focus on responsibility, and I've incorporated 'waves' SVG images as a background-image. The issue arises when viewing the site on smaller screens, such as mobile devices, where the background a ...

Is there a way to determine if a browser supports the offline event?

I attempted to implement the code from this Stack Overflow question: How can I check for support of the `focusin` event? However, in Chromium, the method hasEvent('offline') returns false even though it supports the `offline` event. Does anyone ...

Problem with transitions not working properly in Vue.js.The issue

Experiencing an issue with the Vue.js transition feature. Check out this link for reference. When the transition enters, it works smoothly, but when transitioning out, it's not functioning properly. File: genetic.vue <transition name="slide-f ...

Utilizing AngularJS ng-show to conditionally display content based on data retrieved from an

I am facing an issue with implementing the ngShow directive in my code, where I am trying to display data fetched from an API call. However, despite everything else working correctly, the ngShow directive does not seem to be functioning as expected. Here ...

What is the easiest way to update the border color of a radio button in Material-UI?

I am looking to customize the appearance of the outer ring on Material UI radio buttons. https://material-ui.com/components/radio-buttons/ Currently, my radio button looks like this: https://i.stack.imgur.com/o67mN.jpg However, I would like it to look ...

Certain iFrame instances are unable to display specific cross-domain pages

I'm currently working on a project to create a website that can embed external cross-domain sites, essentially like building a browser within a browser. I've been experimenting with using iFrames for this purpose: While it works for some pages, ...

Express JS backend causing CSS file to fail to load in React project

After doing some research on Stack Overflow, I came across a few solutions but none of them seemed to work for my specific situation. I am currently attempting to serve my React website from an Express backend server. Here is the layout of my folders: cli ...

Issue with background image not resizing or repeating correctly on mobile devices

My website header is not scaling properly on mobile devices, causing some issues. The background color with white text using Bootstrap and custom CSS is not extending across the screen on smartphones or when viewed in Chrome Dev Tools. As a result, two ma ...

Showing tags with varying sizes

Is there a better way to organize and display my content? I have an array of elements that I want to display like the example above. I attempted using lists, but it didn't work out as expected. Here's what I've tried: <div class="row" ...

Detecting click events in D3 for multiple SVG elements within a single webpage

My webpage includes two SVG images inserted using D3.js. I am able to add click events to the SVGs that are directly appended to the body. However, I have encountered an issue with another "floating" div positioned above the first SVG, where I append a dif ...

Having trouble accessing the height of a div within an Iframe

Here is the issue I am facing: I need my iFrame to adjust its size based on a div within it, but every attempt to retrieve the size of this div results in 0. var childiFrame = document.getElementById("myDiv"); console.log(childiFra ...

Error message in JS/Ajax alert box

I keep receiving an alert box saying "Image uploaded" even when the variable $imagename is empty. Below is the script in question: <script> function ajax_post1(ca){ var cat = ca; var name = document.getElementById("name").value; var ...

Eliminate borders surrounding WordPress text widgets

Looking for some help with removing the border around the widgets on my home page. Despite my theme's CSS removing borders universally, I thought targeting specific Div text widgets (such as text-7, text-6) would do the trick. While I can control the ...

Tips for customizing ngTable with expandable detail panels

I am currently working on styling a layout using ng-table, which includes a table within each row. The expanding functionality in Angular is implemented as follows: <tr ng-if="org.expanded" ng-repeat-end> <td></td> <td></td& ...

What are some ways I can enhance the typography within Material UI?

Currently, I am in the process of developing a custom theme utilizing createMuiTheme. However, my application requires more typography variants than what Material UI provides out of the box. I need to extend the typography so that it aligns with my specifi ...