Utilizing Bootstrap and flexbox to create a card: repositioning the image to the left or right

Currently, I am attempting to construct a card layout using Bootstrap 4 with flexbox enabled. The image below depicts my current implementation, which is functioning as expected.

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

Here is the HTML structure:

<section>
  <div class="container">
    <div class="row">
      <div class="col-md-6">
        <div class="card">
          <div class="card-block">
            <h4 class="card-title">Curabitur gravida vestibulum imperdiet.</h4>
            <p class="card-text">Cras convallis ut turpis vitae facilisis. Morbi eu augue vel quam efficitur rhoncus vitae eget lectus. Cras augue ligula, aliquam ut enim ut, feugiat imperdiet sem. Integer sed mi quis nisl eleifend interdum.</p>
            <p class="card-text">Cras convallis ut turpis vitae facilisis. Morbi eu augue vel quam efficitur rhoncus vitae eget lectus. Cras augue ligula, aliquam ut enim ut, feugiat imperdiet sem.</p>
            <a href="#" class="btn btn-primary">Read More</a>
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <img class="card-img-bottom" src="img1.jpg" alt="" title="">
      </div>
    </div>
  </div>
</section>

However, when I view this layout on a larger screen, the output displayed is not what I desire:

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

What I envision instead is:

https://i.sstatic.net/75aE7.jpg

My question now is how can I properly implement this specific layout? My aim is to have both columns cover 100% of the parent height without any padding between them, while maintaining the aspect ratio of the image as shown in the example (cropped from the center).

I have explored various solutions but they all appear complex or hacky. Could it be that there is no straightforward way to achieve this layout?

Note: The solution does not necessarily need to be Bootstrap-specific; a general solution for this type of problem would be preferable.

Answer №1

Exciting Update: Bootstrap Now Fully Supports Horizontal Cards!

A while back, I submitted a feature request for horizontal cards on Bootstrap. You can check it out here: https://github.com/twbs/bootstrap/issues/20794. Today, Bootstrap officially has support and documentation for horizontal cards.

The implementation in Bootstrap involves a mix of grid and utility classes:

<div class="card mb-3" style="max-width: 540px;">
  <div class="row no-gutters">
    <div class="col-md-4">
      <img src="..." class="card-img" alt="...">
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">Card title</h5>
        <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
        <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
      </div>
    </div>
  </div>
</div>

The approach remains similar to what I initially proposed. However, you may need some adjustments depending on your specific card content, as mentioned in the documentation: "Further adjustments may be needed depending on your card content".

Innovative Solution

I discovered an alternative way to achieve this using background-size: cover. By making a small tweak in the HTML structure, I managed to eliminate the need for an image tag. Here's how I modified the code:

<section>
  <div class="container">
    <div class="card">
      <div class="row">
        <div class="col-md-6">
          <div class="card-block">
            <h4 class="card-title">Curabitur gravida vestibulum imperdiet.</h4>
            <p class="card-text">Cras convallis ut turpis vitae facilisis. Morbi eu augue vel quam efficitur rhoncus vitae eget lectus. Cras augue ligula, aliquam ut enim ut, feugiat imperdiet sem. Integer sed mi quis nisl eleifend interdum.</p>
            <p class="card-text">Cras convallis ut turpis vitae facilisis. Morbi eu augue vel quam efficitur rhoncus vitae eget lectus. Cras augue ligula, aliquam ut enim ut, feugiat imperdiet sem.</p>
            <a href="#" class="btn btn-primary">Read More</a>
          </div>
        </div>
        <div class="col-md-6">
          <div class="card-img-bottom">
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

For the card-img-bottom class, I defined the following style:

.card-img-bottom {
  color: #fff;
  height: 20rem;
  background: url(images/img1.jpg) center no-repeat;
  background-size: cover;
}

In the desktop view, I adjusted the height to 100% to ensure consistency with the card-block height.

There might be a slight padding disparity between card-block and card-img-bottom due to default Bootstrap settings, resulting in a slightly larger empty space than the actual image size. Personally, this wasn't a concern for me so I left it as is.

https://i.sstatic.net/Fjc65.png

Answer №2

After some exploration, I've come across a solution to my current issue with image height, although it's not without its own challenges.

The downside of trying to innovate something that is already well-established is that the solutions often bring about new problems, especially when original features are required. In my case, I decided to introduce a new class that would work in conjunction with an existing class. This addition would ensure that if the "card-img-left" class was present, the "card-body" class would automatically adjust its left margin based on the size of the left-aligned image. If the class was not present, then the margin would remain at its default setting. It's a feasible workaround that shouldn't interfere with the core functionality, but there's still room for improvement...

.card {
  overflow: hidden;
}

.card-img-left {
    position: absolute;
    height: auto;
    max-height: 100%;
    width: auto;
    max-width: 40%;
}

.card-img-left ~ .card-body {
    margin-left: 40%;
}

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

"Showcasing a pair of icons side by side in an HTML layout

I need assistance with formatting two legends on the form. I want both legends to be displayed side by side instead of one on top of the other. Here's how I want it: -----legendOne---LegendTwo----- What CSS code do I use to achieve this layout? Be ...

How can I prevent anchors from performing any action when clicked in React?

My dilemma involves this HTML element: <a href onClick={() => fields.push()}>Add Email</a> The purpose of the href attribute is to apply Bootstrap styles for link styling (color, cursor). The issue arises when clicking on the element caus ...

What steps do I need to take in order to successfully make a checkbox?

I am attempting to use Angularjs to set a checkbox to true. When saved, it should store an integer value (1 or 0) in my field. Below is the code snippet for the view: <input type="checkbox" ng-model="lis.SMSPromotion" id="SMSPromotion" ng-init="checke ...

The background image fails to load in ReactJS application

Usually, I have no trouble finding solutions to my problems, but this time I'm really stuck - and I apologize in advance if my question seems silly or trivial. I am currently working on a simple React app where I need to set a background image for th ...

Positioning an HTML control on top of a Silverlight Application, ensuring it moves in sync with the application as it scrolls

   I am facing a challenge with my Silverlight Application (VS2010/C#) that runs in full screen mode.    There is also an HTML control positioned over the Silverlight Application.    When I maximize the brows ...

Challenges with displaying css/bootstrap classes within angular2

Experiencing difficulties with CSS/Bootstrap integration when displayed in an angular2 component. When attempting to display the CSS and HTML content in the Index.html file (with proper CSS and JS references), everything functions correctly. However, once ...

A guide on wrapping text within a Material-UI MenuItem

I am struggling to display text in a popover in multiple lines for UI reasons. I have tried updating the code but so far, I have not been successful. Any suggestions? <Popover anchorEl={target} open={open} anchorOrigin={{ horizontal: 'middle& ...

CSS style takes precedence over inline JavaScript transitions occurring from a negative position

I am puzzled by a JavaScript fiddle I created which contains two small boxes inside a larger box. Upon clicking either of the buttons labeled "Run B" or "Run C", the corresponding box undergoes a CSS transition that is controlled by JavaScript. Below is t ...

The close button is not functioning properly

I created a script to close my div element by clicking on the 'x' icon, but instead of deleting the div only, the whole page gets deleted. I'm not sure where I went wrong, can anyone help me? HTML <div class="note"> <span id ...

Discovering the correct element and typing for an HTML attribute through JavaScript

We are currently working on test automation and I am looking for a way to identify the Element and Type associated with it within an html (Data-qa) attribute. For example, when looping through, the Element is identified as input and the type is radio. < ...

Rotating through elements in timed intervals

After exploring various examples of how to show/hide divs with a JavaScript timeout, I am still unable to resolve my specific issue. I currently have six divs that I want to cycle through sequentially every 10 seconds, starting with div #one. Although my ...

Slider with Dual Images: A Visual Comparison

I'm currently working on a webpage that features before and after images using a slider based on mouse movement to display both pictures. I am trying to incorporate multiple sliders on the same page but have been facing difficulties in getting them to ...

Selenium web scraping falls short in fully extracting all the data needed

Struggling to extract bond information from a webpage using Selenium. Despite successfully retrieving data for some rows in the table, certain rows and columns remain unscraped. The reason behind this inconsistency is unclear. The target webpage can be fo ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

How to Show Byte Array Image in AngularJS HTML Using a Web API Service

I am in the process of developing an AngularJS Application and for my service, I am utilizing .NET C# for coding purposes. I am currently following the code structure outlined in a previous post about loading images from a C# Byte array and placing them in ...

Banner Text Alignment Issue: Uneven Left Alignment

Struggling to achieve consistent text alignment on a ribbon banner? Check out the issue I'm facing and see if you have any suggestions on fixing it: Link to Codepen Main issues: The first line of text appears slightly more indented on the left side ...

Creating a customizable Sass Mixin for animation keyframes that incorporates various stages and the transform property

My goal is to generate the standard CSS using a SASS Mixin for efficiency. STANDARD CSS @-webkit-keyframes crank-up { 100% { -webkit-transform: rotate(360deg);} } @-moz-keyframes crank-up { 100% { -moz-transform: rotate(360deg);} } @-o-keyframes cran ...

How can I code a script to import JSON data into MongoDB database?

I have a JSON file named "data.json" that contains an array of people's names as shown below: "data": [ { { "name":"John", "age":30, } { "name":"Mark", "age":45, } } ] I am ...

Maintain the background color of the form select drop down even after clicking away from the form

I have customized a dropdown menu. <select name="country"> <option value="Andorra">Andorra</option> <option value="Albania">Albania</option> <option value="Armenia">Armenia</option> <opt ...

Issue: potentially harmful data utilized in a URL resource setting

Looking for some assistance - I'm attempting to embed a YouTube video onto my HTML page, but encountered an error message that reads: "Error: unsafe value used in a resource URL context." Upon reviewing my code, everything appears to be correct, and ...