Home > Enterprise >  Text inside container keeps floating a bit to the top
Text inside container keeps floating a bit to the top

Time:09-02

I have a problem with positioning a text inside its container. I want to keep it exactly in the middle, so both justifying and aligning. So I would like it to look like so:

What I do is:

        <div className="view-container">
            <div className="view-icon-container">
                <img className="view-icon" width={icon.size} height={icon.size} src={icon.src} />
            </div>
            <div className="view-text-container">
                <p className="view-text">Text</p>
            </div>
        </div>

with the following styling:

.view-container {
  padding: 5px;
  height: 50px;
  width: 250px;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  border:1px solid black;
}
.view-icon {
  position: absolute;
  border:1px solid black;
}
.view-text {
  width: 100px;
  font-size: 16px;
  text-align: center;
  margin-top: 7px;
  position: absolute;
  align-content: center;
  align-self: center;
  align-items: center;
  border:1px solid black;
}
.view-text-container {
  height: 50px;
  width: 150px;
  display: flex;
  text-align: center;
  justify-content: center;
  align-items: center;
  border:1px solid black;
}
.view-icon-container {
  height: 50px;
  width: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  border:1px solid black;
}

Notice please the 7px margin-top applied to the view-text. My issue is that without it, the text goes to the top a bit, so it looks like so:

enter image description here

My question is: What is causing this margin, or padding to appear? Where does it hide in my CSS?

CodePudding user response:

I think the issue is using the p tag. replace it with a div. Most tags have predefined defaults. You have probably not cancelled some of them when you are using the paragraph.

If you right-click on the page and select Inspect. Select the p element. On the right-hand side you will see your attributes and the browser's defaults. This may or may not be the HTML Specification defaults. And these may change over time.

However, if you are working on margins etc, then you could start off by specifying

margin:0
padding:0 
  • Related