Home > Mobile >  Bootstrap and HTML: how to get first row content centered as full width and second row centered usin
Bootstrap and HTML: how to get first row content centered as full width and second row centered usin

Time:09-10

I'd like to be able to get a layout using Bootstrap that looks as follows: enter image description here

My code is:

<div >
    <div >
        <div >foo</div>
    </div>
    <div >
        <div >bar</div>
        <div >baz</div>
    </div>

Unfortunately, I'm getting something that looks like this (notice that "foo" in row 1 is aligned with "bar" in row 2):

enter image description here

How do I achieve the desired result?

Thanks!

CodePudding user response:

According to your code to make it center, you can align the text center and that's all.

<div >
    <div >
        <div >foo</div>
    </div>
    <div >
        <div >bar</div>
        <div >baz</div>
    </div>
</div>

CodePudding user response:

It seems you want to only center the text on the .col-12 from the first .row which you can easily achieve by simply adding the text-center class to that .col-12 element.
Note: the class text-center is a Bootstrap class.

/** just to visually show the changes */

.col-6,
.col-12 {
  border: 1px solid red
}

.col-12 {
  margin-bottom: 20px;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA 058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div >
  <div >
    <div >foo</div>
  </div>
  <div >
    <div >bar</div>
    <div >baz</div>
  </div>
</div>

In case you have an img not a text on the .col-12 element, you might simply add the d-inline-block and your image should be centered thanks to text-ce,ter class that we already applied.

/** just to visually show the changes */

.col-6,
.col-12 {
  border: 1px solid red;
}

.col-12 {
  margin-bottom: 20px;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA 058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div >
  <div >
    <div >
      <img src="https://via.placeholder.com/150" width="150" >
    </div>
  </div>
  <div >
    <div >bar</div>
    <div >baz</div>
  </div>
</div>

Note: the use of d-inline-block is not really required but i used it to ensure cross-browser behavior because each browser might treat the images in a different way. Most of the browsers already set the display property of an image to inline-block already.

The class img-fluid is a Bootstrap class that allows to maintain a responsive image. Learn more about Bootstrap Responsive Images on Bootstrap Docs (BS v4.0).

Learn more about the display property on MDN.

CodePudding user response:

<div >
<div >
    <div >foo</div>
</div>
<div >
    <div >bar</div>
    <div >baz</div>
</div>
  • Related