What is the best way to contain content within a container while still extending its background to full width in CSS?

I'm currently working on a design that resembles:

https://i.sstatic.net/hc5kv.jpg

In this design, the red lines represent the sides of the container. I have enclosed the content section within a container div as follows:

.container {
width: 1200px;
margin: 0 auto;
}

However, I would like the blue background div to extend all the way to the left of the screen while keeping the content inside the container. The challenge lies in finding the best approach to achieve this without breaking the content structure within the container.

Answer №1

To create the desired effect, you can utilize a pseudo element to mimic a background by positioning it appropriately and giving it the correct dimensions.

Here is an example:

* {
  box-sizing: border-box;
}
.container {
  max-width: 400px;
  padding: 20px 0;
  margin: 0 auto;
}
.container:after {
  content:'';
  display: table;
  height: 0;
  clear: both;
}
.w50 {
  float: left;
  width: 50%;
  position: relative;
  z-index: 2;
}
.w50:first-child:before {
    content:'';
    background: #ddd;
    display: block;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    width: 50vw;
    z-index: -1;
}
<div class="container">
  <div class="w50">
    <h2>First child</h2>
    <p>
      Lorem ipsum, dolor sit amet consectetur adipisicing elit. Inventore eum laboriosam nulla amet. Commodi obcaecati ipsum eum, ea numquam reprehenderit quidem maiores corrupti minus accusantium ipsam error labore sint dolorem.
    </p>
        <p>
      Lorem ipsum, dolor sit amet consectetur adipisicing elit. Inventore eum laboriosam nulla amet. Commodi obcaecati ipsum eum, ea numquam reprehenderit quidem maiores corrupti minus accusantium ipsam error labore sint dolorem.
    </p>
        <p>
      Lorem ipsum, dolor sit amet consectetur adipisicing elit. Inventore eum laboriosam nulla amet. Commodi obcaecati ipsum eum, ea numquam reprehenderit quidem maiores corrupti minus accusantium ipsam error labore sint dolorem.
    </p>
        <p>
      Lorem ipsum, dolor sit amet consectetur adipisicing elit. Inventore eum laboriosam nulla amet. Commodi obcaecati ipsum eum, ea numquam reprehenderit quidem maiores corrupti minus accusantium ipsam error labore sint dolorem.
    </p>
    
  </div>
  <div class="w50">
    <h2>Second child</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet tempora illum eligendi, praesentium saepe error itaque reiciendis. Placeat sint quasi ea obcaecati soluta accusamus. Reiciendis incidunt praesentium quidem commodi expedita?</p>
  </div>
</div>

Instructions on achieving this effect:

  • Add position: relative; to the element that requires the background.
  • Include a pseudo-element :before.
  • Apply
    position: absolute;, width: 50vh; top: 0; right: 0; bottom: 0;
    to the pseudo-element.

Answer №2

Check out my solution for your issue. Make sure to adjust the fixed sizes according to your requirements. I recommend viewing the example in full screen mode.

body{
  background-color: #cccccc;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

div.containerA {
  position: relative; 
  top: 100px;
  width: 100%;
  background-color: lightblue;
}

div.containerB {
  width: 800px;
  margin: 0 auto;
  display: flex;
}

div.contentA {
  width: 50%;
  flex: 0 0 50%;
}

div.contentB {
  position: relative;
  right: -100px;
  width: 50%;
  flex: 1;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div class="containerA">
  <div class="containerB">
      <div class="contentA">
      <h1>Title 1</h1>
     <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum </p>
      </div>

       <div class="contentB">
       <h1>Title 2</h1>
      <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum </p>
      </div>
  <div>    
</div>


</body>
</html>

Answer №3

You can create a stylish two-column layout positioned centrally on the screen, each column having a maximum width of half the container size

.article-container{
max-width:1200px;
margin-left:auto;
margin-right:auto;
}
section{
margin-bottom:2rem;}

.article-grid{
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: stretch;
}
article{
flex:1 50%;
display: flex;
font-family: arial;
 }
article:nth-of-type(1){
background-color:blue;
color:white;
justify-content: flex-end;
}
article:nth-of-type(2){
background-color:red;
color:white;
justify-content: flex-start;
}

.article-inner-grid{
max-width: 600px;
}
.article-padding{
padding:2rem;
}

Answer №4

Create a new section element and insert a div tag with the container class inside it. Apply background CSS to the section element and any additional CSS styles you require to the container.

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

Improved method for transferring multiple form input values from a child to a parent window

I am working on a project where I have a child window containing multiple radio buttons. My goal is to send all the selected values from these radio buttons to the parent window. Currently, I am achieving this by creating a JavaScript string that contains ...

Steps to generate a unique URL for launching a Bootstrap Modal directly

I've encountered a problem where I'm trying to trigger a Modal in window B using a URL when clicking on an image link in window A. The image is nested inside an anchor tag like this: <a href="myserver.mydestinationB.com#myModal><img src= ...

Troubleshooting error: Uncaught ReferenceError - Unable to display SVG elements using D3 and d3.slider due to undefined svg

Hey there, I'm currently exploring a D3 Example and trying to create my own slider to display data from a JSON file. I've included everything in a GitHub repository to share the working files without taking up too much space. Here's what I h ...

Align the video element to the top left corner using Bootstrap 4

Just getting started with bootstrap and css. I'm trying to insert a video element into a row class and want it to be positioned at the top left of the row without any margins. Currently, the video is centered vertically with space above it. Ideally, ...

Is the transmission of " " or " " determined by the individual browser, or is it consistent across all browsers?

This issue has been on my mind for ages... every time I build a website with a textarea that allows multiple lines (like a "About Me" section for a user's profile) I find myself constantly writing this cautious code: // Sample C# code... bio = bio.Re ...

Encountering Empty Output When Trying to Save HTML Form Data to Database

I have recently started learning PHP and web development, and I am attempting to build an HTML form that will submit data to MYSQL. After submitting the form and checking phpMyAdmin, it shows that a row has been submitted, but the row is empty. Previously ...

What's the best method for updating a div on a webpage to display the most current information from the database?

In my small blog project, I have implemented a viewcount feature that tracks the number of times a particular post has been viewed. However, the issue I am facing is that the value of viewcount does not update unless the entire page is refreshed. To addres ...

Aligning a pair of <div> elements within a container in a form field

As I attempt to recreate the survey form challenge from FreeCodeCamp.org Projects, I am facing an issue with aligning two <div> elements inside their parent <div> without the second child moving to a new line using CSS properties other than flo ...

Enhancing the Appearance of MUI Date Calendar

I'm in the process of creating a calendar similar to mui's <DateCalendar />, and I want to customize the header from 'S M T W T F S' to 'Sun Mon...' as well as adjust the position of the arrows. Before: https://i.sstat ...

Is there a way to make the menu overlap the logo on the website?

Within my Ruby on Rails Spree application that utilizes the Twitter Bootstrap gem, I have the following code snippet for the header section: <body class="<%= body_class %>" id="<%= @body_id || 'default' %>" data-hook="body"> & ...

Mastering the Art of jQuery and Line Breaks

I've been working on a project where I am struggling to figure out how to proceed. The issue is with a textarea element where the user should input text, and that input should be displayed directly in a span. Currently, when the user presses enter, th ...

What is the best way to incorporate the value of a textbox into a list?

I currently have a list structured like this: <p>Please choose from the following options:</p> <script type="text/javascript"></script> <select id='pre-selected-options1' multiple='multiple'> <opt ...

The owl-carousel navigation feature is ineffective at higher screen resolutions

My current issue involves the navigation in Owl Carousel. The problem arises when the browser window width exceeds 992px, as the navigation disappears. However, for smaller widths, the navigation works fine. Where could the problem lie? Here is the HTML ...

How can I use a jQuery selector to target all class names that start with a specific prefix, even if multiple classes are

I'm exploring a unique selection statement that will identify specific css classes in a single class attribute by using a string prefix. For instance, I am looking to target any class names prefixed with detail- from the set of sample links below. ...

html div elements may not align correctly

Currently, I am in the process of coding a website that contains numerous images. To assist me in organizing and arranging these images, I have turned to angularjs. Initially, everything was progressing smoothly until this issue arose: https://i.sstatic. ...

The background color changes only on a specific page by selecting a color from the color picker

I created a webpage with a color picker that changes the color of the action bar. However, the action bar color only changes once and I want it to change on all other pages as well. Below is the code I used: <h4>Color Picker</h4> <scrip ...

Using CSS, create a layout with a small 2x2 box positioned beside a larger 2x2 box

https://i.sstatic.net/nC2PI.png Can a flexible ul li structure be achieved with flexbox? I attempted to set the width of the squares to 25% and make the 1st, 3rd, or 5th one 50% wide using a combination of float:left, clear[left|right], but the last squar ...

I encountered an issue while using WooCommerce where I needed the "color section" product attribute to be hidden or disabled when a customer clicked on "stock" in the product price. Unfortunately, I'm unsure of how

function hideStock(){ var selected = document.getElementById("stk"); var hidden = document.getElementById("pa_color"); if (selected.onchange=="stock") { hidden.style.display = "none"; } } <table class= ...

Ways to eliminate the child element(s) from a highlighted text portion

I'm currently struggling to figure out how to manipulate text elements within a span. When a user selects a portion of text in a div, I successfully append a span element. However, if the user selects the same text again, I want to remove the existing ...

What is the method for embedding the creation date of a page within a paragraph on Wagtail?

Whenever a page is created in the admin panel of Wagtail, it automatically displays how much time has elapsed since its creation. https://i.stack.imgur.com/6InSV.png I am looking to include the timestamp of the page's creation within a paragraph in ...