Center element horizontally at a specified breakpoint and below

Can I use Bootstrap 4 utilities to horizontally center an element like a <select> within a col at a specific breakpoint and below? I want to achieve this without using custom CSS.

For instance, I want to center a <select> at xs and sm breakpoints, but have it left-aligned at md, lg, and xl breakpoints.

Bootstrap's mx-sm-auto utility only centers the element at the sm breakpoint and above. Here's an example: https://codepen.io/cpj22/pen/QWLZwJd

(Note to editors: I have checked popular answers on SO, all related to horizontally centering inline elements. If there is a similar question, please ensure it refers to block elements as Bootstrap 4 has different utilities for each type)

Answer №1

Being mobile-first is a core principle of Bootstrap 4, with media queries centered around min-width. This design approach means that targeting only specific breakpoints like `xs` and `md` isn't straightforward due to the absence of an `xs` utility size in Bootstrap 4.

But don't worry, you can still customize these rules by introducing additional mobile-first rules for larger breakpoints. By combining the class `ml-md-0` with `mx-auto`, you can remove left margin on `md` and larger breakpoints while keeping the auto margin for `xs` and `sm` breakpoints.

Here's an example to illustrate this concept:

.bg1 {
  background-color: lightgrey;
}

.bg2 {
  background-color: lightblue;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div class="container mt-5">
  <div class="row">
    <div class="col-6 bg1">
      <div class="row">
        <div class="col-6 mx-auto ml-md-0">
          <select class="form-control mt-5 mb-5">
            <option>select one</option>
            <option>select two</option>
          </select>
        </div>
      </div>
    </div>
    <div class="col-6 bg2">
      <div class="row">
        <div class="col-6 col-sm-6">
          &nbsp;
        </div>
      </div>
    </div>
  </div>
</div>

Answer №2

When using auto margins (mx-auto), the goal is to center the entire column within the row, rather than just the select element inside the column. As @ObsidianAge pointed out, resetting the column centering can be done by setting the margins to 0.

     <div class="col-6 bg1">
            <div class="row">
                <div class="col-6 mx-md-0 mx-auto">
                    <select class="form-control mt-5 mb-5">
                        <option>select one</option>
                        <option>select two</option>
                    </select>
                </div>
            </div>
     </div>

However, I question the need for nesting an inner col-6 within the outer col-6. If the sole purpose of the inner col-6 is to control the width of the form-control field, using w-50 for the input and the responsive text alignment utilities (text-center text-md-left) may be simpler. This approach centers the select element inside the column, rather than the column itself.

   <div class="col-6 bg1 text-center text-md-left">
        <select class="w-50 form-control d-inline mt-5 mb-5">
            <option>select one</option>
            <option>select two</option>
        </select>
   </div>

Check out the demonstration here:

Answer №3

Are you interested in replicating this image? Simply use this provided code snippet.

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

.bg{
  background: linear-gradient(to left, lightgrey 50%, lightblue 50%);
  background: -webkit-linear-gradient(to left, lightgrey 50%, lightblue 50%);
}
<!doctype html>
<html lang="en>
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>Hello, world!</title>
  </head>
  <body>
    <div class="container mt-5">
    <div class="row">
      <div class="col-12 bg">
        <div class="row">
          <div class="col-6 mx-sm-auto">
            <select class="form-control mt-5 mb-5">
              <option>select one</option>
              <option>select two</option>
            </select>
          </div>
        </div>
      </div>
    </div>

   
  </body>
</html>

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

Alter the style of a div by clicking on a button

Can the background image of a div be changed by selecting a button outside of the div? For example: HTML <div id="change"></div> <div id="buttons"> <button class="button1">this</button> <button class="button2"> ...

Room on the edges of a div that is positioned absolutely

I would like to create a space of 10px on each side of the #in div, similar to this layout: Check out the code here - live demo: html <div id="out"> <div id="in"></div> </div> css #out { width: 700px; height: 40px; back ...

Altering the color of text in hyperlinks within a list

Recently, I've started exploring CSS styling and I'm curious if there is a more effective way to change the color of link text when they are within a list. Currently, all my links have the same color and I'd like to enhance this aspect. < ...

How can I translate these JQuery functions into vanilla JavaScript?

I am currently in the process of building a configurator using transparent images. The image configurator functions through a basic JQuery function: I have assigned each input element a data attribute called data-Image. This function identifies the data-Im ...

What is the reason behind Bootstrap's size classes becoming ineffective after 5?

Consider this: <div class="container m-5"> is effective, while <div class="container m-9"> does not produce the desired result. It appears that any number greater than 5 does not function as expected. What could be the rea ...

What is causing my navbar's 'ol' element to have a wider width than the

Hello, I have a navigation bar with a dropdown menu using ol. However, when I hover over the list items, the width of the list exceeds that of the ol element. I believe this is due to the white-space: nowrap CSS property, but I want the text in the dropdow ...

Is it possible to position images in a circular layout around a central

I am struggling to position small planetary images around the main logo in a way that creates a satellite-like effect. Despite my efforts with positioning and margins, I have not been successful in achieving the desired look. Additionally, when I insert th ...

How can I use the store command to retrieve the href value of a link using a css selector in Selenium?

Is there a way to store a URL from a link using CSS instead of xpath? store //tr[td[contains(.,'6 Day')]][1]/td[8]/a@href my_var open $my_var If so, how can I achieve this goal with css? I managed to use the following locator: store css= ...

How can I pass a variable to withStyles in Material UI?

Here is the code I am currently working with: class StyledInput extends React.Component{ styles = (color, theme) => ({ underline: { borderBottom: `2px solid ${color}`, '&:after': { borderBottom: `2px solid ${col ...

Several DIV elements lined up side by side

I've been working on a program that retrieves data from a database, lists some of the data when a button is clicked within the same div, and then creates new divs with buttons that have onclick events until it reaches a certain maximum value. To keep ...

Tips on eliminating extra whitespace in cards

I have created a card with an image and some content, but there seems to be unwanted space between the two elements. How can I remove this space so it looks consistent across all devices? Here is the HTML code: <div class="project-card hidden" ...

What are the best practices for integrating Bootstrap into Lit-Element?

Looking to integrate Lit-Element with Bootstrap, I've already imported the necessary external dependencies following the guidelines mentioned here: Is there a more efficient approach to importing these external dependencies? Below is the code for my ...

Disable the ability to select text when double-clicking

Is there a way to prevent text selection on double click while still allowing selection on mouse drag? Whenever I try to remove selection on dblclick or mouseup, it flashes, which is not the desired outcome as shown in this jsfiddle. UPD: I am not lookin ...

Centering a Font Awesome icon within its parent element

Below is the code I am using: <div style="width:60px; height:60px; background-color: lightgrey;"> <a class="" href="javascript:void(0)" style="color: black; width: inherit; height: inherit;"> <i class="fa fa-lg fa-play" aria-hidden="t ...

What are the steps for incorporating Bootstrap with React.js?

After installing the bootstrap dependency in /node_modules/bootstrap using npm, I included a CDN link in my index.html file. However, I am facing issues with certain tags that are not recognized, and I'm unsure if these tags are part of Bootstrap or ...

What is the method for updating the value of the Sass variable in Angular 4?

Within the file app.component.scss, there is a variable named $color that has been set to 'red'. What steps can be taken within the file app.component.ts in order to access this variable and change its value to 'green'? ...

Encasing the bootstrap dropdown menu and trigger within individual parent divs for a tidier appearance

Is it possible to toggle a bootstrap dropdown when it is wrapped in another div by using attributes such as data-target or aria-labelledby? I have seen examples where data-toggle="dropdown" and class="dropdown-menu" are siblings. An example of what I am r ...

Struggling with z-index or float issues on Chrome and Safari with CSS styling

Check out my website at I have incorporated the Easy Slider 1.7 plugin from this source and made some custom JavaScript modifications for a banner rotator. The issue I am facing is that on webkit browsers, the navigation links (1,2,3,4,5) on the banner a ...

Confirming Bootstrap - Implement an onConfirm method for element attributes

I am looking to add a JavaScript function to my confirmation button. I have created the elements off-page and fetched them using ajax, so it is crucial that I can set the function in-properties rather than via $('#id').confirmation() So far, I h ...

Utilizing JavaScript to assign a CSS class to an <li> list item

I am working on a page that includes a menu feature: https://jsfiddle.net/dva4zo8t/ When a menu button is clicked, the color changes and I need to retain this color even after the page is reloaded: $('[id*="button"]').click(function() { $( ...