Home > Back-end >  Why can't I center my "a" element which I'm using to close a modal component?
Why can't I center my "a" element which I'm using to close a modal component?

Time:09-24

I created an "a" element that closes a modal when clicked on by taking you to the home page. I made it look like a close button. However, I can't seem to vertically center the "X" in it. I tried enclosing it inside a "button" element but that caused other problems. Below is the code:

:root {
  --main-color: #ffc40c;
  --secondary-color: lightyellow;
  --main-red: #d9001d;
  --secondary-red: #ff033e;
  --dark-color: #444;
  --light-color: #fafafa;
}
body {
  font-family: "Source Code Pro", monospace;
  background-color: var(--light-color);
  color: var(--dark-color);
  margin-top: 50px;
  margin-left: 0;
  margin-right: 0;
  margin-bottom: 0;
  text-shadow: 1px 1px 5px var(--light-color);
}
a {
  text-decoration: none;
}
.close-button {
  height: 30px;
  width: 30px;
  background-color: var(--light-color);
  color: var(--main-red);
  margin-left: 0.5em;
  border: 2px solid var(--main-red);
  border-radius: 50%;
  font-weight: 700;
  text-align: center;
}
.close-modal {
  position: fixed;
  top: 2.8em;
  right: 1.7em;
}
<a class="close-button close-modal" href="#!"> X </a>

How do I vertically center it?

CodePudding user response:

Try using flexbox for aligning items.

I added :

display:flex;
justify-content:center;
align-items:center;

to your .close-button class.

Here's the result.

:root {
  --main-color: #ffc40c;
  --secondary-color: lightyellow;
  --main-red: #d9001d;
  --secondary-red: #ff033e;
  --dark-color: #444;
  --light-color: #fafafa;
}
body {
  font-family: "Source Code Pro", monospace;
  background-color: var(--light-color);
  color: var(--dark-color);
  margin-top: 50px;
  margin-left: 0;
  margin-right: 0;
  margin-bottom: 0;
  text-shadow: 1px 1px 5px var(--light-color);
}
a {
  text-decoration: none;
}
.close-button {
display:flex;  /*flexbox a.k.a flexible layout */
justify-content:center; /*for horizontally centering*/
align-items:center; /* for vertically centering*/
  height: 30px;
  width: 30px;
  background-color: var(--light-color);
  color: var(--main-red);
  margin-left: 0.5em;
  border: 2px solid var(--main-red);
  border-radius: 50%;
  font-weight: 700;
  text-align: center;
}
.close-modal {
  position: fixed;
  top: 2.8em;
  right: 1.7em;
}
<a class="close-button close-modal" href="#!"> X </a>

CodePudding user response:

You need add padding-top: 10px for your a tag

CodePudding user response:

a super easy way to center these things is display: grid; place-items: center; try adding these attributes to .close-button

  • Related