What are some ways I can optimize my Bootstrap CSS code to enhance responsiveness across different page widths?

After creating this fiddle, I noticed that my webpage layout with two texts stacked on top of each other looks great on wide screens. However, when the screen size is reduced or viewed on a mobile device, the layout gets all messed up. Take a look at this screenshot for reference: https://i.sstatic.net/AYlwc.png

I initially considered using CSS media queries to make it more responsive and added various styles for different screen widths in my code:

@media (max-width: 545px) {
  ...
}

@media (max-width: 435px) {
  ...
}

@media (max-width: 378px) {
  ...
}

However, managing all these different values for screen sizes seems like a lot of work. Is there a better and more efficient way to ensure that my layout works seamlessly across all devices without the need for specific CSS rules for each screen width? Any suggestions would be greatly appreciated! Thank you!

Answer №1

To prevent the text from adjusting on small screens, set a minimum width and height for each class. Include min-height:123px; and min-width:456px; (adjust pixel values as necessary) to avoid overlapping on smaller resolutions.

Please keep in mind that this may not be ideal for mobile devices.

Answer №2

Within your code snippet, you've specified the height of each div (inner1 and inner2), leading to overflow when the page width is compressed to around 150px. In my experience, setting element heights is not common practice, especially on mobile platforms where width is typically more important.

The issue was resolved for me by adding the overflow attribute in your CSS for each div:

.inner1{
  width:100%;
  height:270px;
  margin-bottom:0px;
overflow: auto;
}
.inner2{
  width:100%;
  height:280px;
  margin-bottom:0px;
  overflow: auto;
}

A helpful resource on the overflow property can be found here, with using "auto" allowing for scrolling without cutting off text: https://developer.mozilla.org/en-US/docs/Web/CSS/overflow

Bootstrap offers a grid system designed specifically to adjust width values responsively based on screen size:

Additionally, setting the viewport width for mobile phones ensures that the CSS is displayed at the actual screen width rather than the pixel density width: https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag

Answer №3

The issue you are encountering is due to the excessive content in .inner1 overflowing and appearing in .inner2. This overflow happens because of the height exceeding the specified limit. To resolve this, you can apply the following CSS:

.inner1{
overflow:hidden;  
}

However, I would suggest using a different method for showing/hiding content rather than fixed heights. Using display:none with code (and potentially animation) would be more optimal. But since that goes beyond the scope of your question, I will not delve into it further.

JSFiddle

HTML (with bootstrap)

<div class= "container">
                <div class="row">
                    <div class="col-sm-7 company">
                        <h2>this is my title</h2>
                        <div class="companyDescription" >
                            <div class="outer">
                                <div class="inner1" id="inner1">
                                <h5>"The quick brown fox jumps over the lazy dog" is an English-language pangram—a phrase that contains all of the letters of the alphabet. It is commonly used for touch-typing practice. It is also used to test typewriters and computer keyboards, show fonts, and other applications involving all of the letters in the English alphabet
                                    </h5><h5>Some kind of subtitle</h5>
                                    <h5><a id="readMore" style="cursor: pointer; cursor: hand;">read more...</a></h5>
                                </div>
                                <div class="inner2">
                                    <h5><a id="readLess" style="cursor: pointer; cursor: hand;">...read less</a></h5>
                                    <h5>As the use of typewriters grew in the late 19th century, the phrase began appearing in typing and stenography lesson books as a practice sentence. Early examples of publications which used the phrase include Illustrative Shorthand by Linda Bronson (1888), How to Become Expert in Typewriting: A Complete Instructor Designed Especially for the Remington Typewriter (1890)
                                    </h5>
                                    <h5>the last subtitle.</h5>
                                </div>
                            </div>
                        </div>
                    </div>
                    </div>
                    </div>

CSS

  .company {
  padding-top: 160px;
  color: #000;
}

.companyDescription {
  margin: 20px 0 10px 0;
  overflow:hidden;
}

.outer{
  width:100%;
  height:280px;
  top:0;
  position:relative;
}

.inner1{
  width:100%;
  height:270px;
  margin-bottom:0px;
  overflow:hidden;/*ONLY ONE NEW CSS LINE!*/
}
.inner2{
  width:100%;
  height:280px;
  margin-bottom:0px;
}

Javascript (with jQuery)

$('#readMore').click(function(){
    $('.companyDescription').animate({
        scrollTop:$('#inner1').outerHeight()+30
    }, 1000);
})
$('#readLess').click(function(){
    $('.companyDescription').animate({
        scrollTop:0
    }, 1000);
})

Answer №4

Check out my code snippet, along with the provided link for reference:

JSFiddle

Snippet of HTML Code -

<div class="col-md-12">
  <div class="row">
    <div class="col-md-12 company">
      <h2>Title Here</h2>
      <div class="companyDescription">
        <div class="outer">
          <div class="inner1" id="inner1">
            <h5>"The quick brown fox jumps over the lazy dog" is an English-language pangram—a phrase that contains all of the letters of the alphabet. It is commonly used for touch-typing practice. It is also used to test typewriters and computer keyboards, show fonts, and other applications involving all of the letters in the English alphabet
                                        </h5>
            <h5>Some kind of subtitle</h5>
            <h5><a id="readMore" style="cursor: pointer; cursor: hand;">read more...</a></h5>
          </div>
          <div class="inner2">
            <h5 style="display:none;"><a id="readLess" style="cursor: pointer; cursor: hand;">...read less</a></h5>
            <h5 style="display:none;">Further details about typing history.</h5>
            <h5 style="display:none;">the last subtitle.</h5>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

JavaScript Functionality -

$('#readMore').click(function() {
    $('#readMore').css('display','none');
  $('.inner2').find('h5').css('display','block');
})
$('#readLess').click(function() {
    $('#readMore').css('display','block');
  $('.inner2').find('h5').css('display','none');
})

Answer №5

While Bootstrap already offers top-notch responsive design capabilities, there are ways to enhance responsiveness further by incorporating your own custom classes within HTML tags and utilizing media queries for specific screen widths.

<div class="container class1">
    content here
</div>

<ul class="list-item class2">
  <li> list item </li>
</ul>

To implement additional responsiveness, simply apply your CSS styles to the designated classes class1 and class2.

Thank you!

Answer №6

We have 2 options to consider:

1. Setting a fixed height...

To address the issue of excess white space, you can change the width to a larger value such as 250px, which will accommodate lower resolutions but may lead to too much white space on desktop screens.

.inner1{
  width:100%;
  height:250px;
  margin-bottom:0px;
  overflow: auto;
}
.inner2{
  width:100%;
  height:250px;
  margin-bottom:0px;
  overflow: auto;
}

2. Dynamically calculating height on window resize...

This approach ensures that the layout works well across all resolutions with minimal white space. Here's how:

Start by wrapping the content inside containers like .inner1 and .inner2, using article as an example container. This helps determine the content's height.

Set the height to 100% for both .inner1 and .inner2 elements:

.inner1 {
  width: 100%;
  height: 100%; /* Set height as 100% */
  margin-bottom: 0px;
}
.inner2 {
  width: 100%;
  height: 100%; /* Set height as 100% */
  margin-bottom: 0px;
}

Give .outer container a default height, like 160px:

.outer {
  width: 100%;
  height: 160px;
  top: 0;
  position: relative;
}

And finally, include some JavaScript to make everything function correctly ;)

Update
Instead of using an anonymous function, assign your function to a variable.

On window resize, compare the heights of content in inner1 and inner2, select the greater one using Math.max, add a 25px gutter, and set this as the height of .outer container:

var fixWidths = function() {
    var
      $cDesc = $('.companyDescription');
    $cDesc.find('.outer').css(
      'height',
      Math.max(
        $cDesc.find('.inner1').children('article').outerHeight(),
        $cDesc.find('.inner2').children('article').outerHeight()
      ) + 25 // Maximum of the two
    )
  }

  $(window).resize(fixWidths);
  fixWidths();

Update
Ensure your JS code is wrapped within...

$(function() {
  ...
});

This will wait until the document is fully loaded...

Finally, trigger a resize event programmatically to set the initial state accurately.

A functional demonstration

[Please see the updated fiddle](https://jsfiddle.net/2nexo75j/16/)

Answer №7

Make sure to utilize the clearfix style

<div class="clearfix"></div> 

Answer №8

Have you made sure to add the "jquery-ui-1.10.4.min.js" file? Are all your CSS and JS files in the correct order? I have tested your code with the same styling and scripting, and it is working for me. You can try the code below.

<!DOCTYPE html>
<html>
<head>
    <title>Scroll</title>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>        
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css">
    <script>
        $(document).ready(function () {
            $('#readMore').click(function () {
                $('.companyDescription').animate({
                    scrollTop: $('#inner1').outerHeight() + 30
                }, 1000);
            });
            $('#readLess').click(function () {
                $('.companyDescription').animate({
                    scrollTop: 0
                }, 1000);
            });
        });
    </script>
    <style>
        .company {
            padding-top: 160px;
            color: #000;
        }

        .companyDescription {
            margin: 20px 0 10px 0;
            overflow:hidden;
        }

        .outer{
            width:100%;
            height:280px;
            top:0;
            position:relative;
        }

        .inner1{
            width:100%;
            height:270px;
            margin-bottom:0px;

        }
        .inner2{
            width:100%;
            height:280px;
            margin-bottom:0px;

        }
    </style>
</head>
<body>
    <div class= "container">
        <div class="row">
            <div class="col-sm-7 company">
                <h2>this is my title</h2>
                <div class="companyDescription" >
                    <div class="outer">
                        <div class="inner1" id="inner1">
                            <h5>"The quick brown fox jumps over the lazy dog" is an English-language pangram—a phrase that contains all of the letters of the alphabet. It is commonly used for touch-typing practice. It is also used to test typewriters and computer keyboards, show fonts, and other applications involving all of the letters in the English alphabet
                            </h5><h5>Some kind of subtitle</h5>
                            <h5><a id="readMore" style="cursor: pointer; cursor: hand;">read more...</a></h5>
                        </div>
                        <div class="inner2">
                            <h5><a id="readLess" style="cursor: pointer; cursor: hand;">...read less</a></h5>
                            <h5>As the use of typewriters grew in the late 19th century, the phrase began appearing in typing and stenography lesson books as a practice sentence. Early examples of publications which used the phrase include Illustrative Shorthand by Linda Bronson (1888), How to Become Expert in Typewriting: A Complete Instructor Designed Especially for the Remington Typewriter (1890)
                            </h5>
                            <h5>the last subtitle.</h5>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

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

Step-by-step guide on activating and utilizing file versioning in Firebase Storage

Google Cloud Platform powers Firebase storage, allowing for versioning of files. Within the Firebase console, there are no options related to the GCP bucket. If you access the GCP console, it may not be apparent how to enable versioning in the bucket asso ...

Angular Pause until the variable is ready

I am in the process of developing a new web application service. The first step involves obtaining a token through the rest API. Once this token is obtained, it needs to be sent as a header to retrieve additional information. The issue I'm facing is ...

How can I center the navbar logo and use it as a toggle for collapsing the menu?

This is a simple example of a navigation bar <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class ...

Using Bootstrap to present information with a table

Presenting information in a Bootstrap table with Vue.js I have gathered the necessary data and now I want to showcase it in a table using bootstrap. Currently, I have achieved this using SCSS as shown in the image below: https://i.sstatic.net/XN3Y4.png ...

Is there a way I can edit this text on the backend page?

Currently, I am attempting to implement a scrolling text box on a front-end page that will display the content from a text file named "msg.txt". <div class="scroll-slow"> <?php echo file_get_contents('../msg.txt'); ?> </div> ...

What is the best way to send information using an array of objects?

In my Angular 5 project, I am using the ngx select dropdown package (https://www.npmjs.com/package/ngx-select-dropdown) and I'm wondering how to pass an array of objects instead of an array of strings. Currently, when I do so, it displays [Object Obje ...

CSS - Maximizing One Column's Width While Allocating Percentage Space for Two Columns?

It's been quite some time since I delved into the world of web development and I seem to have forgotten how to tackle this particular issue. Despite hours spent searching online, I've gained knowledge about flex-boxes and other useful tools, but ...

Angular 2's innovative approach to implementing a sticky footer concept

Is there a way to make my footer sticky without being fixed? I attempted using the CSS negative margin trick, but it did not work as expected. In the provided Plunker code, I tried to replicate the issue in my Angular 2 app. The goal is for the footer to s ...

Error encountered using Meteor 1.3 autoform/quickform integration

Having recently transitioned to using Meteor 1.3, I've encountered a few challenges related to debugging due to missing imports or exports in tutorials. This particular issue seems to be in the same vein. I wanted to incorporate the autoform package ...

Creating a draggable element in JavaScript using React

I've been attempting to create a draggable div element, but I'm encountering some perplexing behavior. The code I'm using is directly from w3schools and it functions correctly for them, however, in my implementation, the div always shifts to ...

Converting HTML to CSV using PHP

I need assistance with exporting MySQL fields to CSV. I have successfully exported all fields except the one that contains HTML content. My MySQL table is structured as follows: Name: Address: Profile: The 'Name' and 'Address' fields ...

Guide to using the ng-click function in Angular to set focus on the input in the last row of a table

I am in the process of developing a task management application and I am looking to implement a specific feature: Upon clicking 'Add Task', a new row is automatically added to the table (this part has been completed) and the input field within ...

Retrieve the specific file path of a dependency within the node_modules directory

Can you help me find the exact path of a dependency within a specific node_modules package? Here's an example setup: |- node_modules/ |- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a4b5b7bfb5b3b1f9b594e6fae5fae4"& ...

PHP and AJAX: Combining Powers to Fetch Data

Greetings. I am currently in the process of creating a WordPress plugin that will manually send an email containing WooCommerce Order details to a specified supplier's email address. I am facing a challenge in understanding how to load data when a use ...

Asynchronous Await Eagerly Anticipates Promise Status: <awaiting

Struggling to implement async/await in an express route and encountering issues. Despite referencing various SO posts, it seems like my implementation is correct. Helpers: module.exports = { facebook: function(userId, token) { return new Promise(re ...

Activate JavaScript functions by pressing the enter key, allowing for various searches, AJAX requests, and DataTable displays to occur seamlessly without the need to refresh

I recently developed a web page that integrates an AWS API interface to interact with an RDS Aurora MySQL Serverless database. Users can input a SQL statement and click the Query button, which triggers an AJAX request, returns JSON data, and converts the d ...

The function "toggleHeightAndOpacity" cannot be accessed on this object because it is not defined

I'm attempting to invoke a variable function name, a task I have successfully accomplished many times in the past using code similar to that found here. <script type="text/javascript"> $.fn.toggleHeightAndOpacity = function(show) { ...

When using SuperTest, the Authorization header value may unexpectedly return undefined

Currently, I am working on writing tests using Mocha, Supertest, and Chai. In order for my API's to function properly, they require an Authorization header which can be obtained from req.headers["authorization"]. Below you will find the current setup ...

Storing parent entity along with child entities containing selected properties using ASP.NET Core MVC

Working on an ASP.NET Core MVC web app, I encountered a problem that can be best explained through this example: Let's consider a scenario where the user needs to save information about a book including its title, number of pages, and one or more aut ...

Django Ajax filter displaying issue on HTML page

I'm uncertain about the correctness of my Ajax implementation. When using Django's built-in tags, the objects I pass through Ajax are not appearing on my template HTML page. view_results.html <div> <input id="search" name="search" t ...