'Center a span inside a label
I'm trying to make a radio button with custom style. This is the html/css I have so far and the problem is that the span, which should be the new checkmark, is not centered inside the label:
.custom-radio-btn{
width: 50px;
height: 50px;
border: 5px solid #500357;
border-radius: 50%;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
display: inline-block;
}
.custom-radio-btn input{
display: none;
}
.custom-radio-btn .checkmark{
width: calc(100% - 5px);
height: calc(100% - 5px);
border-radius: 50%;
background-color: #b406c4;
display: none;
}
.custom-radio-btn input:checked + .checkmark{
display: block;
}
<html>
<body>
<label class="custom-radio-btn">
<input type="radio" name="sample">
<span class="checkmark"></span>
</label>
</body>
</html>
Solution 1:[1]
I changed the css rule .custom-radio-btn .checkmark as follows:
/*changed the offset to 4px instead of 5px*/
width: calc(100% - 4px);
height: calc(100% - 4px);
/*added margin to better center the mark*/
margin-top: 2px;
margin-left: 2px;
This is the demo with such mod:
.custom-radio-btn{
width: 50px;
height: 50px;
border: 5px solid #500357;
border-radius: 50%;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
display: inline-block;
}
.custom-radio-btn input{
display: none;
}
.custom-radio-btn .checkmark{
/*changed the offset to 4px instead of 5px*/
width: calc(100% - 4px);
height: calc(100% - 4px);
border-radius: 50%;
background-color: #b406c4;
display: none;
/*added margin to better center the mark*/
margin-top: 2px;
margin-left: 2px;
}
.custom-radio-btn input:checked + .checkmark{
display: block;
}
<html>
<body>
<label class="custom-radio-btn">
<input type="radio" name="sample">
<span class="checkmark"></span>
</label>
</body>
</html>
Solution 2:[2]
I change your height and width then put a margin on it.
.custom-radio-btn{
width: 50px;
height: 50px;
border: 5px solid #500357;
border-radius: 50%;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
display: inline-block;
}
.custom-radio-btn input{
display: none;
}
.custom-radio-btn >.checkmark{
width: 44px;
height: 44px;
border-radius: 50%;
background-color: #b406c4;
display: none;
margin:2.5px auto;
}
.custom-radio-btn input:checked + .checkmark{
display: block;
}
<html>
<body>
<label class="custom-radio-btn">
<input type="radio" name="sample">
<span class="checkmark"> </span>
</label>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diego De Vita |
| Solution 2 | Crystal |
