Home > Net >  How to align a picture and text vertically in css
How to align a picture and text vertically in css

Time:01-18

Hi I am creating a website and I am trying to align a picture and some text vertically, but I am not being able to do this and the picture is only taking 100% space of the website, this is the code:

body {
  width: 100%;
  max-width: 960px;
  margin: 0;
}

div.content {
  width: 100vw;
  display: flex;
}

div.column1 {
  width: 15%;
  background-color: #F7F7F7;
  overflow: hidden;
  height: 100vh;
}

div.column2 {
  width: 70%;
  overflow: hidden;
}

.banner {
  width: 100vw;
  height: 10vh;
}

.container2 {
  display: flex;
}
<div >
  <div >
  </div>
  <div >
    <div >
      <div >
        <img src="img/lobby.jpg" alt="" /> </div>
      <div >
        <p>lorem50gsdgsdsgdgsgdfgdfgdfgdfgfdggsd</p>
      </div>
    </div>
  </div>
  <div >
  </div>
</div>

The website is divided into 3 columns and I am putting the content on the middle one.

Shouldn't the display flex align them vertically? Why is it not working? Thank you in advance!

CodePudding user response:

You need to set align-items:center on flex parent in order to vertically center its children. Check this for more details about flex-container, and this for more general info about flexbox

You can add justify-content:center for horizontal alignment.

CodePudding user response:

Since you are using display: flex to the content div, add just the property align-items:center and your text will be centred vertically:

body {
  width: 100%;
  max-width: 960px;
  margin: 0;
}

div.content {
  width: 100vw;
  display: flex;
  align-items:center;
}

div.column1 {
  width: 15%;
  background-color: #F7F7F7;
  overflow: hidden;
  height: 100vh;
}

div.column2 {
  width: 70%;
  overflow: hidden;
}

.banner {
  width: 100vw;
  height: 10vh;
}

.container2 {
  display: flex;
}
<div >
  <div >
  </div>
  <div >
    <div >
      <div >
        <img src="img/lobby.jpg" alt="" /> </div>
      <div >
        <p>lorem50gsdgsdsgdgsgdfgdfgdfgdfgfdggsd</p>
      </div>
    </div>
  </div>
  <div >
  </div>
</div>

CodePudding user response:

In order to make it work, try to think with me ok? In order to you understand what is happening here: First of all if you have a parent div its children should be one bellow one another

  1. Your first step is to set the div to have flex: 1, flex check it out this website to learn more.
  2. now set the items to be side by side with display: flex
  3. set the same container with justify-content: center and align-items:center
  4. and if you wish to align the div to the middle of your page, try this: margin: 0 auto
  5. Here is where the magic happens: flex-direction: column, check the documentation flex-direction
  • Related